hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
174b7c99db46d9bce676952cdd5b11c9be481544
15,841
h
C
panda/src/egg/eggTexture.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/egg/eggTexture.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
panda/src/egg/eggTexture.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file eggTexture.h * @author drose * @date 1999-01-18 */ #ifndef EGGTEXTURE_H #define EGGTEXTURE_H #include "pandabase.h" #include "eggRenderMode.h" #include "eggFilenameNode.h" #include "eggTransform.h" #include "pset.h" #include "luse.h" /** * Defines a texture map that may be applied to geometry. */ class EXPCL_PANDAEGG EggTexture : public EggFilenameNode, public EggRenderMode, public EggTransform { PUBLISHED: explicit EggTexture(const string &tref_name, const Filename &filename); EggTexture(const EggTexture &copy); EggTexture &operator = (const EggTexture &copy); virtual ~EggTexture(); virtual void write(ostream &out, int indent_level) const; enum Equivalence { E_basename = 0x001, E_extension = 0x002, E_dirname = 0x004, E_complete_filename = 0x007, E_transform = 0x008, E_attributes = 0x010, E_tref_name = 0x020, }; bool is_equivalent_to(const EggTexture &other, int eq) const; bool sorts_less_than(const EggTexture &other, int eq) const; bool has_alpha_channel(int num_components) const; enum TextureType { TT_unspecified, TT_1d_texture, TT_2d_texture, TT_3d_texture, TT_cube_map }; enum Format { F_unspecified, F_rgba, F_rgbm, F_rgba12, F_rgba8, F_rgba4, F_rgba5, F_rgb, F_rgb12, F_rgb8, F_rgb5, F_rgb332, F_red, F_green, F_blue, F_alpha, F_luminance, F_luminance_alpha, F_luminance_alphamask }; enum CompressionMode { CM_default, CM_off, CM_on, CM_fxt1, CM_dxt1, CM_dxt2, CM_dxt3, CM_dxt4, CM_dxt5, }; enum WrapMode { WM_unspecified, WM_clamp, WM_repeat, WM_mirror, WM_mirror_once, WM_border_color }; enum FilterType { // Note that these type values match up, name-for-name, with a similar // enumerated type in Panda's Texture object. However, they do *not* // match up numerically. You must convert between them using a switch // statement. FT_unspecified, // Mag Filter and Min Filter FT_nearest, FT_linear, // Min Filter Only FT_nearest_mipmap_nearest, // "mipmap point" FT_linear_mipmap_nearest, // "mipmap linear" FT_nearest_mipmap_linear, // "mipmap bilinear" FT_linear_mipmap_linear, // "mipmap trilinear" }; enum EnvType { ET_unspecified, ET_modulate, ET_decal, ET_blend, ET_replace, ET_add, ET_blend_color_scale, ET_modulate_glow, ET_modulate_gloss, ET_normal, ET_normal_height, ET_glow, ET_gloss, ET_height, ET_selector, ET_normal_gloss, }; enum CombineMode { CM_unspecified, CM_replace, CM_modulate, CM_add, CM_add_signed, CM_interpolate, CM_subtract, CM_dot3_rgb, CM_dot3_rgba, }; enum CombineChannel { CC_rgb = 0, CC_alpha = 1, CC_num_channels = 2, }; enum CombineIndex { CI_num_indices = 3 }; enum CombineSource { CS_unspecified, CS_texture, CS_constant, CS_primary_color, CS_previous, CS_constant_color_scale, CS_last_saved_result, }; enum CombineOperand { CO_unspecified, CO_src_color, CO_one_minus_src_color, CO_src_alpha, CO_one_minus_src_alpha, }; enum TexGen { TG_unspecified, TG_eye_sphere_map, TG_world_cube_map, TG_eye_cube_map, TG_world_normal, TG_eye_normal, TG_world_position, TG_eye_position, TG_point_sprite, }; enum QualityLevel { QL_unspecified, QL_default, QL_fastest, QL_normal, QL_best, }; INLINE void set_texture_type(TextureType texture_type); INLINE TextureType get_texture_type() const; INLINE void set_format(Format format); INLINE Format get_format() const; INLINE void set_compression_mode(CompressionMode mode); INLINE CompressionMode get_compression_mode() const; INLINE void set_wrap_mode(WrapMode mode); INLINE WrapMode get_wrap_mode() const; INLINE void set_wrap_u(WrapMode mode); INLINE WrapMode get_wrap_u() const; INLINE WrapMode determine_wrap_u() const; INLINE void set_wrap_v(WrapMode mode); INLINE WrapMode get_wrap_v() const; INLINE WrapMode determine_wrap_v() const; INLINE void set_wrap_w(WrapMode mode); INLINE WrapMode get_wrap_w() const; INLINE WrapMode determine_wrap_w() const; INLINE void set_minfilter(FilterType type); INLINE FilterType get_minfilter() const; INLINE void set_magfilter(FilterType type); INLINE FilterType get_magfilter() const; INLINE void set_anisotropic_degree(int anisotropic_degree); INLINE void clear_anisotropic_degree(); INLINE bool has_anisotropic_degree() const; INLINE int get_anisotropic_degree() const; INLINE void set_env_type(EnvType type); INLINE EnvType get_env_type() const; bool affects_polygon_alpha() const; INLINE void set_combine_mode(CombineChannel channel, CombineMode cm); INLINE CombineMode get_combine_mode(CombineChannel channel) const; INLINE void set_combine_source(CombineChannel channel, int n, CombineSource cs); INLINE CombineSource get_combine_source(CombineChannel channel, int n) const; INLINE void set_combine_operand(CombineChannel channel, int n, CombineOperand co); INLINE CombineOperand get_combine_operand(CombineChannel channel, int n) const; INLINE void set_saved_result(bool saved_result); INLINE bool get_saved_result() const; INLINE void set_tex_gen(TexGen tex_gen); INLINE TexGen get_tex_gen() const; INLINE void set_quality_level(QualityLevel quality_level); INLINE QualityLevel get_quality_level() const; INLINE void set_stage_name(const string &stage_name); INLINE void clear_stage_name(); INLINE bool has_stage_name() const; INLINE const string &get_stage_name() const; INLINE void set_priority(int priority); INLINE void clear_priority(); INLINE bool has_priority() const; INLINE int get_priority() const; INLINE void set_color(const LColor &color); INLINE void clear_color(); INLINE bool has_color() const; INLINE const LColor &get_color() const; INLINE void set_border_color(const LColor &border_color); INLINE void clear_border_color(); INLINE bool has_border_color() const; INLINE const LColor &get_border_color() const; INLINE void set_uv_name(const string &uv_name); INLINE void clear_uv_name(); INLINE bool has_uv_name() const; INLINE const string &get_uv_name() const; INLINE void set_rgb_scale(int rgb_scale); INLINE void clear_rgb_scale(); INLINE bool has_rgb_scale() const; INLINE int get_rgb_scale() const; INLINE void set_alpha_scale(int alpha_scale); INLINE void clear_alpha_scale(); INLINE bool has_alpha_scale() const; INLINE int get_alpha_scale() const; INLINE void set_alpha_filename(const Filename &filename); INLINE void clear_alpha_filename(); INLINE bool has_alpha_filename() const; INLINE const Filename &get_alpha_filename() const; INLINE void set_alpha_fullpath(const Filename &fullpath); INLINE const Filename &get_alpha_fullpath() const; INLINE void set_alpha_file_channel(int alpha_file_channel); INLINE void clear_alpha_file_channel(); INLINE bool has_alpha_file_channel() const; INLINE int get_alpha_file_channel() const; INLINE void set_multiview(bool multiview); INLINE bool get_multiview() const; INLINE void set_num_views(int num_views); INLINE void clear_num_views(); INLINE bool has_num_views() const; INLINE int get_num_views() const; INLINE void set_read_mipmaps(bool read_mipmaps); INLINE bool get_read_mipmaps() const; INLINE void set_min_lod(double min_lod); INLINE void clear_min_lod(); INLINE bool has_min_lod() const; INLINE double get_min_lod() const; INLINE void set_max_lod(double max_lod); INLINE void clear_max_lod(); INLINE bool has_max_lod() const; INLINE double get_max_lod() const; INLINE void set_lod_bias(double lod_bias); INLINE void clear_lod_bias(); INLINE bool has_lod_bias() const; INLINE double get_lod_bias() const; void clear_multitexture(); bool multitexture_over(EggTexture *other); INLINE int get_multitexture_sort() const; static TextureType string_texture_type(const string &string); static Format string_format(const string &string); static CompressionMode string_compression_mode(const string &string); static WrapMode string_wrap_mode(const string &string); static FilterType string_filter_type(const string &string); static EnvType string_env_type(const string &string); static CombineMode string_combine_mode(const string &string); static CombineSource string_combine_source(const string &string); static CombineOperand string_combine_operand(const string &string); static TexGen string_tex_gen(const string &string); static QualityLevel string_quality_level(const string &string); PUBLISHED: MAKE_PROPERTY(texture_type, get_texture_type, set_texture_type); MAKE_PROPERTY(format, get_format, set_format); MAKE_PROPERTY(compression_mode, get_compression_mode, set_compression_mode); MAKE_PROPERTY(wrap_mode, get_wrap_mode, set_wrap_mode); MAKE_PROPERTY(wrap_u, get_wrap_u, set_wrap_u); MAKE_PROPERTY(wrap_v, get_wrap_v, set_wrap_v); MAKE_PROPERTY(wrap_w, get_wrap_w, set_wrap_w); MAKE_PROPERTY(minfilter, get_minfilter, set_minfilter); MAKE_PROPERTY(magfilter, get_magfilter, set_magfilter); MAKE_PROPERTY2(anisotropic_degree, has_anisotropic_degree, get_anisotropic_degree, set_anisotropic_degree, clear_anisotropic_degree); MAKE_PROPERTY(env_type, get_env_type, set_env_type); MAKE_PROPERTY(saved_result, get_saved_result, set_saved_result); MAKE_PROPERTY(tex_gen, get_tex_gen, set_tex_gen); MAKE_PROPERTY(quality_level, get_quality_level, set_quality_level); MAKE_PROPERTY2(stage_name, has_stage_name, get_stage_name, set_stage_name, clear_stage_name); MAKE_PROPERTY2(priority, has_priority, get_priority, set_priority, clear_priority); MAKE_PROPERTY2(color, has_color, get_color, set_color, clear_color); MAKE_PROPERTY2(border_color, has_border_color, get_border_color, set_border_color, clear_border_color); MAKE_PROPERTY2(uv_name, has_uv_name, get_uv_name, set_uv_name, clear_uv_name); MAKE_PROPERTY2(rgb_scale, has_rgb_scale, get_rgb_scale, set_rgb_scale, clear_rgb_scale); MAKE_PROPERTY2(alpha_scale, has_alpha_scale, get_alpha_scale, set_alpha_scale, clear_alpha_scale); MAKE_PROPERTY2(alpha_filename, has_alpha_filename, get_alpha_filename, set_alpha_filename, clear_alpha_filename); MAKE_PROPERTY(alpha_fullpath, get_alpha_fullpath, set_alpha_fullpath); MAKE_PROPERTY2(alpha_file_channel, has_alpha_file_channel, get_alpha_file_channel, set_alpha_file_channel, clear_alpha_file_channel); MAKE_PROPERTY(multiview, get_multiview, set_multiview); MAKE_PROPERTY2(num_views, has_num_views, get_num_views, set_num_views, clear_num_views); MAKE_PROPERTY(read_mipmaps, get_read_mipmaps, set_read_mipmaps); MAKE_PROPERTY2(min_lod, has_min_lod, get_min_lod, set_min_lod, clear_min_lod); MAKE_PROPERTY2(max_lod, has_max_lod, get_max_lod, set_max_lod, clear_max_lod); MAKE_PROPERTY2(lod_bias, has_lod_bias, get_lod_bias, set_lod_bias, clear_lod_bias); MAKE_PROPERTY(multitexture_sort, get_multitexture_sort); public: virtual EggTransform *as_transform(); protected: virtual bool egg_start_parse_body(); private: typedef pset<EggTexture *> MultiTextures; bool r_min_multitexture_sort(int sort, MultiTextures &cycle_detector); enum Flags { F_has_alpha_filename = 0x0002, F_has_anisotropic_degree = 0x0004, F_has_alpha_file_channel = 0x0008, F_has_stage_name = 0x0010, F_has_uv_name = 0x0020, F_has_priority = 0x0040, F_has_color = 0x0080, F_has_rgb_scale = 0x0100, F_has_alpha_scale = 0x0200, F_has_border_color = 0x0400, F_has_num_views = 0x0800, F_has_min_lod = 0x1000, F_has_max_lod = 0x2000, F_has_lod_bias = 0x4000, }; TextureType _texture_type; Format _format; CompressionMode _compression_mode; WrapMode _wrap_mode, _wrap_u, _wrap_v, _wrap_w; FilterType _minfilter, _magfilter; int _anisotropic_degree; EnvType _env_type; bool _saved_result; bool _multiview; int _num_views; TexGen _tex_gen; QualityLevel _quality_level; string _stage_name; int _priority; LColor _color; LColor _border_color; string _uv_name; int _rgb_scale; int _alpha_scale; int _flags; Filename _alpha_filename; Filename _alpha_fullpath; int _alpha_file_channel; bool _read_mipmaps; int _multitexture_sort; double _min_lod; double _max_lod; double _lod_bias; class SourceAndOperand { public: INLINE SourceAndOperand(); CombineSource _source; CombineOperand _operand; }; class Combiner { public: INLINE Combiner(); CombineMode _mode; SourceAndOperand _ops[CI_num_indices]; }; Combiner _combiner[CC_num_channels]; // This is the set of all of the textures that are multitextured on top of // (and under) this one. This is filled in by multitexture_over(). MultiTextures _over_textures, _under_textures; public: static TypeHandle get_class_type() { return _type_handle; } static void init_type() { EggFilenameNode::init_type(); EggRenderMode::init_type(); register_type(_type_handle, "EggTexture", EggFilenameNode::get_class_type(), EggRenderMode::get_class_type()); } virtual TypeHandle get_type() const { return get_class_type(); } virtual TypeHandle force_init_type() {init_type(); return get_class_type();} private: static TypeHandle _type_handle; }; /** * An STL function object for sorting textures into order by properties. * Returns true if the two referenced EggTexture pointers are in sorted order, * false otherwise. */ class EXPCL_PANDAEGG UniqueEggTextures { public: INLINE UniqueEggTextures(int eq = ~0); INLINE bool operator ()(const EggTexture *t1, const EggTexture *t2) const; int _eq; }; INLINE ostream &operator << (ostream &out, const EggTexture &n) { return out << n.get_filename(); } EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::TextureType texture_type); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::Format format); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CompressionMode mode); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::WrapMode mode); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::FilterType type); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::EnvType type); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineMode cm); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineChannel cc); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineSource cs); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::CombineOperand co); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::TexGen tex_gen); EXPCL_PANDAEGG ostream &operator << (ostream &out, EggTexture::QualityLevel quality_level); #include "eggTexture.I" #endif
32.394683
101
0.735118
[ "geometry", "object", "3d" ]
174ce877a63d5e20cefebaa26a67e7a0db31d5c4
4,033
h
C
src/Database.h
sylveryte/timewarrior
b450122c9f28c88d578c98c535cecd5c0fe9fd20
[ "MIT" ]
null
null
null
src/Database.h
sylveryte/timewarrior
b450122c9f28c88d578c98c535cecd5c0fe9fd20
[ "MIT" ]
null
null
null
src/Database.h
sylveryte/timewarrior
b450122c9f28c88d578c98c535cecd5c0fe9fd20
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2016, 2018 - 2020, Thomas Lauf, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // https://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #ifndef INCLUDED_DATABASE #define INCLUDED_DATABASE #include <Datafile.h> #include <Interval.h> #include <Range.h> #include <Transaction.h> #include <vector> #include <string> #include <TagInfoDatabase.h> #include <Journal.h> class Database { public: class iterator { private: friend class Database; typedef std::vector <Datafile>::reverse_iterator files_iterator; typedef std::vector <std::string>::const_reverse_iterator lines_iterator; typedef std::string value_type; files_iterator files_it; files_iterator files_end; lines_iterator lines_it; lines_iterator lines_end; iterator (files_iterator fbegin, files_iterator fend); public: iterator& operator++ (); iterator& operator++ (int); iterator& operator-- (); bool operator== (const iterator & other) const; bool operator!= (const iterator & other) const; const value_type& operator* () const; const value_type* operator-> () const; }; class reverse_iterator { private: friend class Database; typedef std::vector <Datafile>::iterator files_iterator; typedef std::vector <std::string>::const_iterator lines_iterator; typedef std::string value_type; files_iterator files_it; files_iterator files_end; lines_iterator lines_it; lines_iterator lines_end; reverse_iterator(files_iterator fbegin, files_iterator fend); public: reverse_iterator& operator++ (); reverse_iterator& operator++ (int); reverse_iterator& operator-- (); bool operator== (const reverse_iterator & other) const; bool operator!= (const reverse_iterator & other) const; const value_type& operator* () const; const value_type* operator-> () const; }; public: Database () = default; void initialize (const std::string&, Journal& journal); void commit (); std::vector <std::string> files () const; std::set <std::string> tags () const; std::string getLatestEntry (); void addInterval (const Interval&, bool verbose); void deleteInterval (const Interval&); void modifyInterval (const Interval&, const Interval &, bool verbose); std::string dump () const; bool empty (); iterator begin (); iterator end (); reverse_iterator rbegin (); reverse_iterator rend (); private: unsigned int getDatafile (int, int); std::vector <Range> segmentRange (const Range&); void initializeDatafiles (); void initializeTagDatabase (); private: std::string _location {"~/.timewarrior/data"}; std::vector <Datafile> _files {}; TagInfoDatabase _tagInfoDatabase {}; Journal* _journal {}; }; #endif
31.023077
81
0.684354
[ "vector" ]
174ed7b45b24fd58a88708390eb8520668af5059
4,395
h
C
include/algorithms.h
theojepsen/nuevomatch
30138b5c7fb2e331b29794d89927106fa8991c42
[ "MIT" ]
28
2020-07-14T13:47:48.000Z
2022-01-22T09:19:01.000Z
include/algorithms.h
theojepsen/nuevomatch
30138b5c7fb2e331b29794d89927106fa8991c42
[ "MIT" ]
2
2021-04-22T21:12:41.000Z
2021-07-18T09:20:35.000Z
include/algorithms.h
theojepsen/nuevomatch
30138b5c7fb2e331b29794d89927106fa8991c42
[ "MIT" ]
15
2020-07-23T12:34:25.000Z
2021-08-05T07:25:53.000Z
/* * MIT License * Copyright (c) 2019 Alon Rashelbach * * 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 algorithms.h */ #pragma once #include <set> // std::set #include <vector> // std::vector #include <basic_types.h> /** * @brief Create random permutation of integers * @param dst Permutation destination location * @param size The size of the permutation * @note Unsafe: the user should allocate dst memory location. */ void random_permutation(uint32_t* dst, uint32_t size); /** * @brief Generates uniform random unsigned integers between low and high * @param The type of the return type. * @param low Low bound (inclusive) * @param high High bound (inclusive) * @note Taken from here https://stackoverflow.com/questions/21096015/how-to-generate-64-bit-random-numbers */ uint32_t gen_uniform_random_uint32(uint32_t low, uint32_t high); /** * @brief Generates uniform random scalars between low and high * @param The type of the return type. * @param low Low bound (inclusive) * @param high High bound (inclusive) * @note Taken from here https://stackoverflow.com/questions/21096015/how-to-generate-64-bit-random-numbers */ scalar_t gen_uniform_random_scalar(scalar_t low, scalar_t high); /** * @brief Compute all possible combinations of all elements in an array of sets. * @param sets An array of sets, each with a list of unique elements * @returns A vector of all possible combinations of the sets' values * @note Complexity: O(n * (a*b*c*...)) for n number of sets, and {a,b,c,...} are set sizes * This is also the total number of elements in the output array. */ template <typename T> std::vector<std::vector<T>> calculate_all_combinations(const std::vector<std::set<T>> &sets) { // How many combinations are there? // Complexity: O(n) for n number of sets uint32_t total_combinations = 1; for (auto current_set : sets) { total_combinations *= current_set.size(); } // Allocate memory for all combinations std::vector<std::vector<T>> output(total_combinations); // Store iterators for all sets // Complexity: O(n) for n number of sets std::vector<typename std::set<T>::const_iterator> iterator_array; uint32_t num_of_sets = sets.size(); for (uint32_t j=0; j<num_of_sets; ++j) { iterator_array.push_back(sets[j].cbegin()); } // Determine division factor per set // Complexity: O(n) for n number of sets std::vector<uint32_t> division_factor; uint32_t accumulator = 1; for (auto current_set : sets) { division_factor.push_back(accumulator); accumulator *= current_set.size(); } // For each possible combinations // Complexity: O(n * (a*b*c*...)) for n number of sets, and {a,b,c,...} are set sizes // Note: this is also the total number of elements in the output array. for (uint32_t i=0; i<total_combinations; ++i) { // Initialize the current combination to hold S elements output[i].resize(num_of_sets); // For each set for (uint32_t j=0; j<num_of_sets; ++j) { // Populate the output with current iterator output[i][j] = *iterator_array[j]; // Calculate the index divided by the current division factor uint32_t idx = i/division_factor[j]; // Update iterator if ((idx + 1) % sets[j].size() == 0) { ++iterator_array[j]; if (iterator_array[j] == sets[j].end()) { iterator_array[j] = sets[j].cbegin(); } } } } return output; }
36.322314
107
0.720137
[ "vector" ]
174f04e690aa57b644fe33cca3c81d9df32a60db
5,521
c
C
wayland.c
SirCmpwn/mako
31d975d8c79efed60756737d7f2c8c1d18d89f29
[ "MIT" ]
1
2019-01-16T03:47:23.000Z
2019-01-16T03:47:23.000Z
wayland.c
ddevault/mako
31d975d8c79efed60756737d7f2c8c1d18d89f29
[ "MIT" ]
null
null
null
wayland.c
ddevault/mako
31d975d8c79efed60756737d7f2c8c1d18d89f29
[ "MIT" ]
null
null
null
#include <stdio.h> #include "mako.h" #include "notification.h" #include "render.h" #include "wayland.h" static void noop() { // This space intentionally left blank } static void pointer_handle_button(void *data, struct wl_pointer *pointer, uint32_t serial, uint32_t time, uint32_t button, uint32_t button_state) { struct mako_state *state = data; if (button_state != WL_POINTER_BUTTON_STATE_PRESSED || wl_list_empty(&state->notifications)) { return; } struct mako_notification *first_notif = wl_container_of(state->notifications.next, first_notif, link); close_notification(first_notif, MAKO_NOTIFICATION_CLOSE_DISMISSED); send_frame(state); } static const struct wl_pointer_listener pointer_listener = { .enter = noop, .leave = noop, .motion = noop, .button = pointer_handle_button, .axis = noop, }; static void seat_handle_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) { struct mako_state *state = data; if (capabilities & WL_SEAT_CAPABILITY_POINTER) { struct wl_pointer *pointer = wl_seat_get_pointer(seat); wl_pointer_add_listener(pointer, &pointer_listener, state); } } static const struct wl_seat_listener seat_listener = { .capabilities = seat_handle_capabilities, }; static void layer_surface_configure(void *data, struct zwlr_layer_surface_v1 *surface, uint32_t serial, uint32_t width, uint32_t height) { struct mako_state *state = data; state->width = width; state->height = height; zwlr_layer_surface_v1_ack_configure(surface, serial); send_frame(state); } static void layer_surface_closed(void *data, struct zwlr_layer_surface_v1 *surface) { struct mako_state *state = data; state->running = false; } static const struct zwlr_layer_surface_v1_listener layer_surface_listener = { .configure = layer_surface_configure, .closed = layer_surface_closed, }; static void handle_global(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t version) { struct mako_state *state = data; if (strcmp(interface, wl_compositor_interface.name) == 0) { state->compositor = wl_registry_bind(registry, name, &wl_compositor_interface, 3); } else if (strcmp(interface, wl_shm_interface.name) == 0) { state->shm = wl_registry_bind(registry, name, &wl_shm_interface, 1); } else if (strcmp(interface, zwlr_layer_shell_v1_interface.name) == 0) { state->layer_shell = wl_registry_bind(registry, name, &zwlr_layer_shell_v1_interface, 1); } else if (strcmp(interface, wl_seat_interface.name) == 0) { struct wl_seat *seat = wl_registry_bind(registry, name, &wl_seat_interface, 1); wl_seat_add_listener(seat, &seat_listener, state); } } static void handle_global_remove(void *data, struct wl_registry *registry, uint32_t name) { // who cares } static const struct wl_registry_listener registry_listener = { .global = handle_global, .global_remove = handle_global_remove, }; bool init_wayland(struct mako_state *state) { state->display = wl_display_connect(NULL); state->registry = wl_display_get_registry(state->display); wl_registry_add_listener(state->registry, &registry_listener, state); wl_display_roundtrip(state->display); if (state->compositor == NULL) { fprintf(stderr, "compositor doesn't support wl_compositor\n"); return false; } if (state->shm == NULL) { fprintf(stderr, "compositor doesn't support wl_shm\n"); return false; } if (state->layer_shell == NULL) { fprintf(stderr, "compositor doesn't support zwlr_layer_shell_v1\n"); return false; } state->surface = wl_compositor_create_surface(state->compositor); state->layer_surface = zwlr_layer_shell_v1_get_layer_surface( state->layer_shell, state->surface, NULL, ZWLR_LAYER_SHELL_V1_LAYER_TOP, "notifications"); zwlr_layer_surface_v1_add_listener(state->layer_surface, &layer_surface_listener, state); struct mako_config *config = &state->config; int32_t margin = config->margin; zwlr_layer_surface_v1_set_size(state->layer_surface, config->width, config->height); zwlr_layer_surface_v1_set_anchor(state->layer_surface, ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT); zwlr_layer_surface_v1_set_margin(state->layer_surface, margin, margin, margin, margin); wl_surface_commit(state->surface); return true; } void finish_wayland(struct mako_state *state) { zwlr_layer_surface_v1_destroy(state->layer_surface); wl_surface_destroy(state->surface); destroy_buffer(&state->buffers[0]); destroy_buffer(&state->buffers[1]); wl_shm_destroy(state->shm); zwlr_layer_shell_v1_destroy(state->layer_shell); wl_compositor_destroy(state->compositor); wl_registry_destroy(state->registry); wl_display_disconnect(state->display); } void send_frame(struct mako_state *state) { state->current_buffer = get_next_buffer(state->shm, state->buffers, state->width, state->height); int height = render(state, state->current_buffer); if (height == 0) { // Unmap the surface wl_surface_attach(state->surface, NULL, 0, 0); wl_surface_commit(state->surface); return; } // TODO: if the compositor doesn't send a configure with the size we // requested, we'll enter an infinite loop if (state->height != height) { zwlr_layer_surface_v1_set_size(state->layer_surface, state->config.width, height); wl_surface_commit(state->surface); return; } wl_surface_attach(state->surface, state->current_buffer->buffer, 0, 0); wl_surface_damage(state->surface, 0, 0, state->width, state->height); wl_surface_commit(state->surface); }
29.524064
77
0.764354
[ "render" ]
1751b1f94456a59b90b0098eb47eb4cc785ce13a
1,417
h
C
languages/cpp/inc/element_read_map.h
fatash89/atom
12846c8a3f936ae6c83e7e7b1d2dbb896e63fe66
[ "Apache-2.0" ]
64
2019-04-01T20:32:07.000Z
2021-11-24T17:12:03.000Z
languages/cpp/inc/element_read_map.h
elementary-robotics/atom
36aea078c0e029f03e7b9b4768729a683fb32a88
[ "Apache-2.0" ]
291
2019-04-01T22:54:31.000Z
2022-03-31T21:48:47.000Z
languages/cpp/inc/element_read_map.h
fatash89/atom
12846c8a3f936ae6c83e7e7b1d2dbb896e63fe66
[ "Apache-2.0" ]
5
2019-06-27T22:42:54.000Z
2022-02-01T23:00:37.000Z
//////////////////////////////////////////////////////////////////////////////// // // @file element_read_map.h // // @brief Map of streams to handlers // // @copy 2018 Elementary Robotics. All rights reserved. // //////////////////////////////////////////////////////////////////////////////// #ifndef __ATOM_CPP_ELEMENT_READ_MAP #define __ATOM_CPP_ELEMENT_READ_MAP #include "atom/atom.h" #include "atom/redis.h" #include "element_response.h" #include <map> namespace atom { // Forward declaration for the entry class class Entry; // Read handler function typedef bool (*readHandlerFn)( Entry &e, void *user_data); // Typedef the tuple typedef std::tuple<std::string, std::string, std::vector<std::string>, readHandlerFn, void*> handler_t; // Response class class ElementReadMap { std::vector<handler_t> handlers; public: // Constructor and destructor ElementReadMap(); ~ElementReadMap(); // Add in a handler void addHandler( std::string element, std::string stream, std::vector<std::string> keys, readHandlerFn fn); // Add in a handler with user data void addHandler( std::string element, std::string stream, std::vector<std::string> keys, readHandlerFn fn, void *user_data); // Gets the number of handlers size_t getNumHandlers(); // Gets the info for a particular handler handler_t &getHandler(int n); }; } // namespace atom #endif // __ATOM_CPP_ELEMENT_READ_MAP
21.149254
103
0.641496
[ "vector" ]
17559112429881aa666ebe9288a637f19380f7b2
7,680
c
C
src/util_sum.c
jeremie-mb/ludwig
78be393d9d270b7dca019083ba1a2e0e92ffafe9
[ "BSD-3-Clause" ]
null
null
null
src/util_sum.c
jeremie-mb/ludwig
78be393d9d270b7dca019083ba1a2e0e92ffafe9
[ "BSD-3-Clause" ]
null
null
null
src/util_sum.c
jeremie-mb/ludwig
78be393d9d270b7dca019083ba1a2e0e92ffafe9
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * * util_sum.c * * Compensated sums. File to be compiled at -O0. * * Edinburgh Soft Matter and Statistical Physics Group and * Edinburgh Parallel Computing Centre * * (c) 2021 The University of Edinburgh * * Contributing authors: * Kevin Stratford (kevin@epcc.ed.ac.uk) * *****************************************************************************/ #include <assert.h> #include <math.h> #include "util_sum.h" /***************************************************************************** * * kahan_add_double * * Add a contribution to a simple compensated sum. * *****************************************************************************/ __host__ __device__ void kahan_add_double(kahan_t * kahan, double val) { assert(kahan); { volatile double y = val + kahan->cs; volatile double t = kahan->sum + y; kahan->cs = y - (t - kahan->sum); kahan->sum = t; } } /***************************************************************************** * * kahan_zero * *****************************************************************************/ __host__ __device__ kahan_t kahan_zero(void) { kahan_t k = {0, 0.0, 0.0}; return k; } /***************************************************************************** * * kahan_sum * *****************************************************************************/ __host__ __device__ double kahan_sum(const kahan_t * sum) { assert(sum); return (sum->sum + sum->cs); } /***************************************************************************** * * klein_zero * * Return zero object. * *****************************************************************************/ __host__ __device__ klein_t klein_zero(void) { klein_t sum = {0, 0.0, 0.0, 0.0}; return sum; } /***************************************************************************** * * klein_add_double * * Add a contribution to a doubly compensated sum. * *****************************************************************************/ __host__ __device__ void klein_add_double(klein_t * klein, double val) { assert(klein); { volatile double c; volatile double cc; volatile double t = klein->sum + val; if (fabs(klein->sum) >= fabs(val)) { c = (klein->sum - t) + val; } else { c = (val - t) + klein->sum; } klein->sum = t; t = klein->cs + c; if (fabs(klein->cs) >= fabs(c)) { cc = (klein->cs - t) + c; } else { cc = (c - t) + klein->cs; } klein->cs = t; klein->ccs = klein->ccs + cc; } return; } /***************************************************************************** * * klein_sum * * Convenience to return doubly compensated sum. * *****************************************************************************/ __host__ __device__ double klein_sum(const klein_t * klein) { assert(klein); return klein->sum + klein->cs + klein->ccs; } /***************************************************************************** * * kahan_add * *****************************************************************************/ __host__ __device__ void kahan_add(kahan_t * sum, kahan_t val) { assert(sum); kahan_add_double(sum, val.sum); kahan_add_double(sum, val.cs); return; } /***************************************************************************** * * klein_add * *****************************************************************************/ __host__ __device__ void klein_add(klein_t * sum, klein_t val) { assert(sum); klein_add_double(sum, val.sum); klein_add_double(sum, val.cs); klein_add_double(sum, val.ccs); return; } /***************************************************************************** * * kahan_mpi_datatype * * Generate datatype handle. Caller to release via MPI_Datatype_free(). * *****************************************************************************/ __host__ int kahan_mpi_datatype(MPI_Datatype * type) { int blocklengths[3] = {1, 1, 1}; MPI_Aint displacements[4] = {}; MPI_Datatype types[3] = {MPI_INT, MPI_DOUBLE, MPI_DOUBLE}; kahan_t sum = {}; assert(type); MPI_Get_address(&sum, displacements + 0); MPI_Get_address(&sum.lock, displacements + 1); MPI_Get_address(&sum.sum, displacements + 2); MPI_Get_address(&sum.cs, displacements + 3); /* Subtract the offset (displacements[0] == displacements[1] in fact) */ for (int n = 1; n <= 3; n++) { displacements[n] -= displacements[0]; } MPI_Type_create_struct(3, blocklengths, displacements + 1, types, type); MPI_Type_commit(type); return 0; } /***************************************************************************** * * kahan_mpi_op_sum_function * * Implementation for sum operation below. * *****************************************************************************/ __host__ void kahan_mpi_op_sum_function(kahan_t * invec, kahan_t * inoutvec, int * len, MPI_Datatype * dt) { assert(invec); assert(inoutvec); assert(len); assert(dt); for (int n = 0; n < *len; n++) { kahan_add(inoutvec + n, invec[n]); } return; } /***************************************************************************** * * kahan_mpi_op_sum * * Return the MPI_Op for the sum above. Caller to MPI_Op_free(). * *****************************************************************************/ __host__ int kahan_mpi_op_sum(MPI_Op * op) { assert(kahan_mpi_op_sum_function); assert(op); MPI_Op_create((MPI_User_function *) kahan_mpi_op_sum_function, 0, op); return 0; } /***************************************************************************** * * klein_mpi_datatype * * Generate a datatype handle. Caller to release via MPI_Datatype_free(). * *****************************************************************************/ __host__ int klein_mpi_datatype(MPI_Datatype * type) { int ierr = 0; int blocklengths[4] = {1, 1, 1, 1}; MPI_Aint displacements[5] = {}; MPI_Datatype types[4] = {MPI_INT, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE}; klein_t sum = {}; assert(type); MPI_Get_address(&sum, displacements + 0); MPI_Get_address(&sum.lock, displacements + 1); MPI_Get_address(&sum.sum, displacements + 2); MPI_Get_address(&sum.cs, displacements + 3); MPI_Get_address(&sum.ccs, displacements + 4); /* Subtract the offset (displacements[0] == displacements[1] in fact) */ for (int n = 1; n <= 4; n++) { displacements[n] -= displacements[0]; } MPI_Type_create_struct(4, blocklengths, displacements + 1, types, type); MPI_Type_commit(type); return ierr; } /***************************************************************************** * * klein_mpi_op_sum_function * * Implementation for sum operation below. * *****************************************************************************/ __host__ void klein_mpi_op_sum_function(klein_t * invec, klein_t * inoutvec, int * len, MPI_Datatype * dt) { assert(invec); assert(inoutvec); assert(len); assert(dt); for (int n = 0; n < *len; n++) { klein_add(inoutvec + n, invec[n]); } return; } /***************************************************************************** * * klein_mpi_op_sum * * Return the MPI_Op for the sum above. Caller to MPI_Op_free(). * *****************************************************************************/ __host__ int klein_mpi_op_sum(MPI_Op * op) { assert(klein_mpi_op_sum_function); assert(op); MPI_Op_create((MPI_User_function *) klein_mpi_op_sum_function, 0, op); return 0; }
24
79
0.445052
[ "object" ]
1756054a86d217ad56eeaaff0174389f513874cf
4,039
h
C
content/renderer/media/cdm_session_adapter.h
Acidburn0zzz/chromium-1
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/cdm_session_adapter.h
Acidburn0zzz/chromium-1
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/cdm_session_adapter.h
Acidburn0zzz/chromium-1
4c08f442d2588a2c7cfaa117a55bd87d2ac32f9a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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 CONTENT_RENDERER_MEDIA_CDM_SESSION_ADAPTER_H_ #define CONTENT_RENDERER_MEDIA_CDM_SESSION_ADAPTER_H_ #include <map> #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "media/base/media_keys.h" #include "third_party/WebKit/public/platform/WebContentDecryptionModuleSession.h" #if defined(ENABLE_PEPPER_CDMS) #include "content/renderer/media/crypto/pepper_cdm_wrapper.h" #endif class GURL; namespace content { class WebContentDecryptionModuleSessionImpl; // Owns the CDM instance and makes calls from session objects to the CDM. // Forwards the session ID-based callbacks of the MediaKeys interface to the // appropriate session object. Callers should hold references to this class // as long as they need the CDM instance. class CdmSessionAdapter : public base::RefCounted<CdmSessionAdapter> { public: CdmSessionAdapter(); // Returns true on success. bool Initialize( #if defined(ENABLE_PEPPER_CDMS) const CreatePepperCdmCB& create_pepper_cdm_cb, #endif const std::string& key_system, const GURL& security_origin); // Creates a new session and adds it to the internal map. The caller owns the // created session. RemoveSession() must be called when destroying it. WebContentDecryptionModuleSessionImpl* CreateSession( blink::WebContentDecryptionModuleSession::Client* client); // Removes a session from the internal map. void RemoveSession(uint32 session_id); // Initializes the session specified by |session_id| with the |content_type| // and |init_data| provided. void InitializeNewSession(uint32 session_id, const std::string& content_type, const uint8* init_data, int init_data_length); // Updates the session specified by |session_id| with |response|. void UpdateSession(uint32 session_id, const uint8* response, int response_length); // Releases the session specified by |session_id|. void ReleaseSession(uint32 session_id); // Returns the Decryptor associated with this CDM. May be NULL if no // Decryptor is associated with the MediaKeys object. // TODO(jrummell): Figure out lifetimes, as WMPI may still use the decryptor // after WebContentDecryptionModule is freed. http://crbug.com/330324 media::Decryptor* GetDecryptor(); #if defined(OS_ANDROID) // Returns the CDM ID associated with the |media_keys_|. May be kInvalidCdmId // if no CDM ID is associated. int GetCdmId() const; #endif private: friend class base::RefCounted<CdmSessionAdapter>; typedef std::map<uint32, WebContentDecryptionModuleSessionImpl*> SessionMap; ~CdmSessionAdapter(); // Callbacks for firing session events. void OnSessionCreated(uint32 session_id, const std::string& web_session_id); void OnSessionMessage(uint32 session_id, const std::vector<uint8>& message, const std::string& destination_url); void OnSessionReady(uint32 session_id); void OnSessionClosed(uint32 session_id); void OnSessionError(uint32 session_id, media::MediaKeys::KeyError error_code, uint32 system_code); // Helper function of the callbacks. WebContentDecryptionModuleSessionImpl* GetSession(uint32 session_id); // Session ID should be unique per renderer process for debugging purposes. static uint32 next_session_id_; scoped_ptr<media::MediaKeys> media_keys_; SessionMap sessions_; #if defined(OS_ANDROID) int cdm_id_; #endif // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<CdmSessionAdapter> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(CdmSessionAdapter); }; } // namespace content #endif // CONTENT_RENDERER_MEDIA_CDM_SESSION_ADAPTER_H_
34.521368
81
0.739787
[ "object", "vector" ]
175c18d310789d59385cfb3f9850da107fae1309
221,756
c
C
sdk-6.5.20/src/bcm/esw/helix5/ft_field.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/esw/helix5/ft_field.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/bcm/esw/helix5/ft_field.c
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: ft_field.c * Purpose: Flowtracker module specific routines in flowtracker * stage in FP. */ #include <soc/defs.h> #if defined (BCM_FLOWTRACKER_SUPPORT) && defined (BCM_FIELD_SUPPORT) #include <bcm/error.h> #include <bcm/field.h> #include <shared/bsl.h> #include <shared/pack.h> #include <bcm/flowtracker.h> #include <bcm_int/esw/field.h> #include <bcm_int/esw/udf.h> #include <bcm_int/esw/tomahawk.h> #include <bcm_int/esw/helix5.h> #include <bcm_int/esw/keygen_api.h> #include <bcm_int/esw/flowtracker/ft_interface.h> #include <bcm_int/esw_dispatch.h> /* Internal MACRO to goto cleanup. */ #define BCMI_IF_ERROR_CLEANUP(_rv_) \ do { \ if (_rv_ != BCM_E_NONE) { \ goto cleanup; \ } \ } while(0) /* Macro to add group tracking elements map to database. */ #define _FP_FT_TRACKING_PARAM_QUAL_MAP_DECL \ _field_ft_tracking_param_qual_map_t _pq_map_ /* Macro to add tracking param to qualifier mapping database. */ #define _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(_unit_, _map_db_, _flags_, \ _param_, _qual_, _start_, _width_, _ft_type_bmp_) \ do { \ _field_ft_tracking_param_qual_map_init((_unit_), &_pq_map_); \ _pq_map_.flags = (_flags_); \ _pq_map_.param = (_param_); \ _pq_map_.qual = (_qual_); \ _pq_map_.start = (_start_); \ _pq_map_.width = (_width_); \ _pq_map_.db_ft_type_bmp = (_ft_type_bmp_); \ rv = _field_ft_tracking_param_qual_map_insert((_unit_), \ (_param_), &(_pq_map_), (_map_db_)); \ BCMI_IF_ERROR_CLEANUP(rv); \ } while(0) /* Tracking param is not mapped to qualifier. */ #define _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED (1 << 0) /* Tracking param requires ALU 16-bit. */ #define _FP_FT_TRACKING_PARAM_F_ALU16_REQ (1 << 1) /* Tracking param required ALU 32-bit. */ #define _FP_FT_TRACKING_PARAM_F_ALU32_REQ (1 << 2) /* Tracking Param is mapped for ALU Data */ #define _FP_FT_TRACKING_PARAM_F_ALU_DATA (1 << 3) /* Tracking Param requires modulo 32 for Key */ #define _FP_FT_TRACKING_PARAM_F_KEY_MODULO_32 (1 << 4) /* Tracking Param requires modulo 32 for Data */ #define _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32 (1 << 5) /* Tracking Param does not generate Session Key/Data */ #define _FP_FT_TRACKING_PARAM_F_NO_FILL (1 << 6) /* Tracking param requires udf object */ #define _FP_FT_TRACKING_PARAM_F_UDF_MAPPED (1 << 7) /* Tracking Param may use 8b extractors for Data */ #define _FP_FT_TRACKING_PARAM_F_DATA_USE_GRAN8 (1 << 8) /* Tracking param required ALU. */ #define _FP_FT_TRACKING_PARAM_F_ALU_REQ \ (_FP_FT_TRACKING_PARAM_F_ALU16_REQ | \ _FP_FT_TRACKING_PARAM_F_ALU32_REQ) /* Tracking info type is param info. */ #define _FP_FT_TRACKING_INFO_TYPE_PARAM (1 << 0) /* Tracking info type is flowcheck info. */ #define _FP_FT_TRACKING_INFO_TYPE_FLOWCHECK (1 << 1) /* Tracking info type is Alu data info */ #define _FP_FT_TRACKING_INFO_TYPE_ALU_DATA (1 << 2) /* Start Index of ALU Data in param_qual_map db */ #define _FP_FT_TRACKING_ALU_DATA_PARAM_MAP_START \ (_FIELD_FT_TRACKING_ELEMENT_TYPE_MAX) /* * Typedef: * _field_ft_tracking_alu_data_info_t * Purpose: * ALU Data related tracking information. */ typedef struct _field_ft_tracking_alu_data_info_s { /* ALU Data param */ uint16 param; /* Corresponding qualifier */ bcm_field_qualify_t qual; /* Offset within the qualifier */ int offset; /* Width of ALU Data param */ int width; /* Position after extraction */ int extract_pos; } _field_ft_tracking_alu_data_info_t; /* FT Group Keygen Extraction process States */ #define _FIELD_FT_GROUP_KEYGEN_START 0 #define _FIELD_FT_GROUP_KEYGEN_CFG_ALLOC 1 #define _FIELD_FT_GROUP_KEYGEN_CFG_ALU_QUAL_ADD 2 #define _FIELD_FT_GROUP_KEYGEN_CFG_FC_QUAL_ADD 3 #define _FIELD_FT_GROUP_KEYGEN_CFG_DATA_KEY_QUAL_ADD 4 #define _FIELD_FT_GROUP_KEYGEN_CFG_DATA_QUAL_ADJUST 5 #define _FIELD_FT_GROUP_KEYGEN_CFG_KEY_QUAL_ADJUST 6 #define _FIELD_FT_GROUP_KEYGEN_DATA_OPER_EXTRACT 7 #define _FIELD_FT_GROUP_KEYGEN_KEY_OPER_EXTRACT 8 #define _FIELD_FT_GROUP_KEYGEN_DATA_OPER_PROCESS 9 #define _FIELD_FT_GROUP_KEYGEN_KEY_OPER_PROCESS 10 #define _FIELD_FT_GROUP_KEYGEN_MFT_DATA_PROCESS 11 #define _FIELD_FT_GROUP_KEYGEN_EFT_DATA_PROCESS 12 #define _FIELD_FT_GROUP_KEYGEN_OPER_SAVE 13 #define _FIELD_FT_GROUP_KEYGEN_END 14 /* * Typedef: * _field_ft_group_keydata_udf_param_t * Purposes: * UDF tracking params related information */ typedef struct _field_ft_group_keydata_udf_param_s { /* UDF Data qualifier */ int qual_id; /* Tracking param */ bcm_flowtracker_tracking_param_type_t param; /* Custom Id */ uint16 custom_id; /* Chunk bitmap (2b per chunk) */ uint32 chunk_hw_bmap; } _field_ft_group_keydata_udf_param_t; /* * Typedef: * _field_ft_group_keydata_keygen_md_t * Purpose: * Session key/data extraction related information. */ typedef struct _field_ft_group_keydata_keygen_md_s { /* List of allowed keygen mode for extraction. */ bcmi_keygen_mode_t ext_modes[2]; /* Number of valid indices in ext_modes. */ int ext_modes_count; /* Keygen_cfg->qual_info_arr. */ bcmi_keygen_qual_info_t *qual_info_arr; /* Corresponding to tracking param info index */ uint16 qual_param_idx_arr[30]; /* Total memory allocated to qual_info_arr. */ uint16 max_qual_info_alloc; /* Actual number of qual info in qual_info_arr. */ uint16 qual_info_count; /* Qset of qualifiers in qual_info_arr. */ bcm_field_qset_t qset; /* Keygen_oper information after extraction. */ bcmi_keygen_oper_t keygen_oper; /* Actual extraction Keygen mode. */ bcmi_keygen_mode_t keygen_mode; /* Number of keygen parts. */ uint16 num_parts; /* Udf data qualifier index to use */ int next_data_qual_idx; /* Number of valid UDF param maps */ int num_udf_maps; /* UDF data qualifiers mappings */ _field_ft_group_keydata_udf_param_t param_udf_map[16]; } _field_ft_group_keydata_keygen_md_t; /* * Typedef: * _field_ft_group_keygen_oper_info_t * Purpose: * Session key/data extraction information * in the form required by FT module. */ typedef struct _field_ft_group_keygen_oper_info_s { /* keygen mode of session key. */ int mode; /* Number of Session key info. */ int num_skey_info; /* Session key info. */ bcmi_ft_group_alu_info_t *skey_info; /* Number of elements in skey_ext_info. */ int skey_ext_count; /* Encoded session Key ext codes. */ bcmi_ft_hw_extractor_info_t *skey_ext_info; /* Number of Session data info. */ int num_sdata_info; /* Session data info. */ bcmi_ft_group_alu_info_t *sdata_info; /* Number of elements in sdata_ext_info. */ int sdata_ext_count; /* Encoded Session data ext codes. */ bcmi_ft_hw_extractor_info_t *sdata_ext_info; } _field_ft_group_keygen_oper_info_t; /* Keygen flag for Session Key Extraction */ #define _FIELD_FTG_KEYGEN_F_KEY_REQ (1 << 0) /* Keygen flag for Session Data Extraction */ #define _FIELD_FTG_KEYGEN_F_DATA_REQ (1 << 1) /* Keygen flag for Session Alu data Extraction */ #define _FIELD_FTG_KEYGEN_F_ALU_DATA_REQ (1 << 2) /* * Typedef: * _field_ft_group_keygen_md_t * Purpose: * metadata for FT group keygen extraction for * session key and session data. */ typedef struct _field_ft_group_keygen_md_s { uint32 flags; /* Current processing state in _FIELD_FT_GROUP_KEYGEN_XXX. */ uint16 state; /* Previous processing state in _FIELD_FT_GROUP_KEYGEN_XXX. */ uint16 prev_state; /* Return code for current processing state. */ int state_rv; /* FT information in field stage struct. */ _field_ft_info_t *ft_info; /* FT Group Identifier. */ bcm_flowtracker_group_t ft_group_id; /* Number of elements in tracking_params_info. */ int num_tracking_params; /* List of tracking params info for FT Group. */ bcm_flowtracker_tracking_param_info_t *tracking_params_info; /* Number of elements in flowtracker_checks. */ int num_flowchecks; /* List of flowcheck Ids for FT Group/ */ bcm_flowtracker_check_t *flowtracker_checks; /* Number of ALU data elements. */ int num_alu_data; /* Pointer to ALU Data info. */ _field_ft_tracking_alu_data_info_t *alu_data_info; /* Metadata for session key keygen. */ _field_ft_group_keydata_keygen_md_t skey_keygen_md; /* Metadata for session data keygen. */ _field_ft_group_keydata_keygen_md_t sdata_keygen_md; /* Operational info for key/data extraction. */ _field_ft_group_keygen_oper_info_t keydata_oper_info; /* Ft Type Bitmap */ uint16 ft_type_bmp; /* Set if output is required to saved to FT Group DB. */ uint8 save_op; } _field_ft_group_keygen_md_t; /* * Typedef: * _bcm_field_ft_entry_traverse_cb * Purpose: * Callback function pointer per entry in flowtracke stage. */ typedef int (*_bcm_field_ft_entry_traverse_cb)(int unit, bcm_field_entry_t entry, bcm_flowtracker_group_t id, void *user_data1, void *user_data2); /* Local functions */ #if defined(BCM_FLOWTRACKER_V2_SUPPORT) STATIC int _field_ft_mmu_tracking_param_qual_map_db_init(int unit, _field_ft_tracking_param_qual_map_db_t *map_db); STATIC int _field_ft_egr_tracking_param_qual_map_db_init(int unit, _field_ft_tracking_param_qual_map_db_t *map_db); #endif /* * Function: * _field_ft_keygen_udf_chunk_hw_bmap_get * Purpose: * Get chunk hw bitmap based on offset/width * Parameters: * unit - (IN) BCM device number. * offset - (IN) Offset within UDF object (in bytes) * width - (IN) Required width (in bytes) * chunk_bmap - (IN) UDF chunk bitmap * chunk_hw_bmap - (OUT) Chunk hw bitmap (2b per chunk) * Returns: */ STATIC int _field_ft_keygen_udf_chunk_hw_bmap_get(int unit, uint16 offset, uint16 width, uint32 chunk_bmap, uint32 *chunk_hw_bmap) { int chunk = 0; int rem_width = width; int rem_offset = offset; #define _FP_FT_UDF_TOTAL_CHUNKS 16 #define _FP_FT_UDF_CHUNK_BYTES 2 chunk = 0; while ((chunk < _FP_FT_UDF_TOTAL_CHUNKS) && (rem_width > 0)) { if (chunk_bmap & (1 << chunk)) { if (rem_offset >= _FP_FT_UDF_CHUNK_BYTES) { /* Skip both byes of the chunk */ rem_offset -= _FP_FT_UDF_CHUNK_BYTES; } else if (rem_offset == 1) { /* Skip first byte of the chunk. Add second byte */ (*chunk_hw_bmap) |= (0x2 << (chunk * _FP_FT_UDF_CHUNK_BYTES)); rem_width -= 1; rem_offset -= 1; } else if (rem_width >= _FP_FT_UDF_CHUNK_BYTES) { /* Add both bytes of the chunk */ (*chunk_hw_bmap) |= (0x3 << (chunk * _FP_FT_UDF_CHUNK_BYTES)); rem_width -= _FP_FT_UDF_CHUNK_BYTES; } else if (rem_width == 1) { /* Add only first byte of the chunk */ (*chunk_hw_bmap) |= (0x1 << (chunk * _FP_FT_UDF_CHUNK_BYTES)); rem_width -= 1; } } chunk++; } return BCM_E_NONE; } /* * Function: * _field_ft_group_keygen_param_udf_map_add * Purpose: * Add udf param map to keygen md for extraction * Parameters: * unit - (IN) BCM device number. * keydata_keygen_md - (IN) Session key/data md * param - (IN) Tracking param * custom_id - (IN) Custom Id of the tracking param * qual_id - (OUT) Qualifier for the param * index - (OUT) Insert index * new_qual - (OUT) If newly inserted * Returns: * BCM_E_xxx */ STATIC int _field_ft_group_keygen_param_udf_map_add(int unit, _field_ft_group_keydata_keygen_md_t *keydata_keygen_md, bcm_flowtracker_tracking_param_type_t param, uint16 custom_id, uint16 *qual_id, int *index, int *new_qual) { int rv = BCM_E_NONE; int idx = 0, found = FALSE; int data_qual_idx = 0; uint32 param_udf_hw_bmap = 0; _bcm_udf_td3_obj_info_t *obj_info = NULL; bcm_flowtracker_udf_info_t param_udf_info; _field_ft_group_keydata_udf_param_t *param_udf_map = NULL; uint16 data_qual_list[] = { _bcmFieldQualifyData0, _bcmFieldQualifyData1, _bcmFieldQualifyData2, _bcmFieldQualifyData3, _bcmFieldQualifyData4, _bcmFieldQualifyData5, _bcmFieldQualifyData6, _bcmFieldQualifyData7, _bcmFieldQualifyData8, _bcmFieldQualifyData9, _bcmFieldQualifyData10, _bcmFieldQualifyData11, _bcmFieldQualifyData12, _bcmFieldQualifyData13, _bcmFieldQualifyData14, _bcmFieldQualifyData15 }; /* Get param udf mapping */ rv = bcm_esw_flowtracker_udf_tracking_param_get(unit, 0, param, custom_id, &param_udf_info); BCM_IF_ERROR_RETURN(rv); /* Get UDF object info */ rv = _bcm_udf_td3_object_info_get(unit, param_udf_info.udf_id, &obj_info); BCM_IF_ERROR_RETURN(rv); /* Get valid param UDF chunk hw bitmap */ _field_ft_keygen_udf_chunk_hw_bmap_get(unit, param_udf_info.offset/8, param_udf_info.width/8, obj_info->chunk_bmap, &param_udf_hw_bmap); /* Validate hw bitmap against previous maps */ for (idx = 0, found = FALSE; idx < keydata_keygen_md->num_udf_maps; idx++) { param_udf_map = &keydata_keygen_md->param_udf_map[idx]; if ((param_udf_map->param == param) && (param_udf_map->custom_id == custom_id) && (param_udf_map->chunk_hw_bmap == param_udf_hw_bmap)) { found = TRUE; break; } /* Current hw bitmap conflict with previos hw bitmap */ if (param_udf_map->chunk_hw_bmap & param_udf_hw_bmap) { return BCM_E_CONFIG; } } /* Add to the map list if not found */ if (found == FALSE) { if (keydata_keygen_md->next_data_qual_idx >= COUNTOF(data_qual_list)) { return BCM_E_INTERNAL; } data_qual_idx = keydata_keygen_md->next_data_qual_idx; param_udf_map = &keydata_keygen_md->param_udf_map[idx]; param_udf_map->param = param; param_udf_map->custom_id = custom_id; param_udf_map->chunk_hw_bmap = param_udf_hw_bmap; param_udf_map->qual_id = data_qual_list[data_qual_idx]; keydata_keygen_md->num_udf_maps++; keydata_keygen_md->next_data_qual_idx++; *new_qual = TRUE; } else { param_udf_map = &keydata_keygen_md->param_udf_map[idx]; *new_qual = FALSE; } *qual_id = param_udf_map->qual_id; *index = idx; return BCM_E_NONE; } /* * Function: * _field_ft_group_keygen_udf_qual_cfg_init * Purpose: * Init data qualifier in keygen qual cfg db * Parameters: * unit - (IN) BCM device number. * qual_cfg_info_db - (IN) Keygen qual cfg db * qual_id - (IN) Data qualifier Id * chunk_hw_bmap - (IN) Chunk hw bitmap for data qualifier * qual_width - (OUT) Width of the qualifier * qual_cfg_parts- (OUT) Number of parts of quaifier config in db * Returns: * BCM_E_xxx */ STATIC int _field_ft_group_keygen_udf_qual_cfg_init(int unit, bcmi_keygen_qual_cfg_info_db_t *qual_cfg_info_db, uint16 qual_id, uint32 chunk_hw_bmap, int *qual_width, int *qual_cfg_parts) { uint8 hw_bmap = 0; int chunk = 0, cfg_num = 0; int offset = 0, qual_bits = 0; bcmi_keygen_qual_flags_bmp_t qual_flags; /* UDF Opaque fields in Ingress Field Bus */ int in_field_bus_opaque_offset[] = { 784, 768, 752, 736, 720, 704, 688, 672, 944, 928, 896, 872, 848, 832, 816, 800 }; BCMI_KEYGEN_FUNC_ENTER(unit); BCMI_KEYGEN_QUAL_CFG_DECL; BCMI_KEYGEN_QUAL_CFG_INIT(unit); sal_memset(&qual_flags, 0, sizeof(bcmi_keygen_qual_flags_bmp_t)); for (chunk = (_FP_FT_UDF_TOTAL_CHUNKS - 1); chunk >= 0; chunk--) { /* Get hw bitmap */ hw_bmap = (chunk_hw_bmap >> (chunk * _FP_FT_UDF_CHUNK_BYTES)) & 0x3; qual_bits = 0; offset = in_field_bus_opaque_offset[chunk]; switch(hw_bmap) { case 0x1: /* Second byte */ offset += 8; qual_bits = 8; break; case 0x2: /* First byte */ qual_bits = 8; break; case 0x3: /* Both bytes */ qual_bits = 16; break; default: /* None */ break; } if (qual_bits == 0) { continue; } /* Update Qualifier Width */ *qual_width += qual_bits; /* If offset is non-multiple of 16, add single byte */ if ((offset % 16) != 0) { BCMI_KEYGEN_QUAL_CFG_OFFSET_ADD(cfg_num, BCMI_KEYGEN_EXT_SECTION_L1E16, offset / 16, offset, 8); qual_bits -= 8; offset += 8; cfg_num++; } /* Add qual cfg */ if (qual_bits != 0) { BCMI_KEYGEN_QUAL_CFG_OFFSET_ADD(cfg_num, BCMI_KEYGEN_EXT_SECTION_L1E16, offset / 16, offset, qual_bits); cfg_num++; } } BCMI_KEYGEN_QUAL_CFG_INSERT(unit, qual_cfg_info_db, qual_id, qual_flags); *qual_cfg_parts = cfg_num; exit: BCMI_KEYGEN_FUNC_EXIT(); } /* * Function: * _field_ft_group_param_udf_qual_init * Purpose: * Init data qualifier for given <param, custom>. * Parameters: * unit - (IN) BCM device number. * keydata_keygen_md - (IN) Session key/data md * param - (IN) Tracking param * custom_id - (IN) Custom Id of the tracking param * qual_id - (OUT) Qualifier for the param * flags - (OUT) Qualifier flags * Returns: */ STATIC int _field_ft_group_param_udf_qual_init(int unit, bcmi_keygen_qual_cfg_info_db_t *qual_cfg_info_db, _field_ft_group_keydata_keygen_md_t *keydata_keygen_md, bcm_flowtracker_tracking_param_type_t param, uint16 custom_id, bcm_field_qualify_t *qual, uint32 *flags) { int rv = 0; int index = 0; int qual_cfg_parts = 0; int qual_width = 0; int new_qual = FALSE; uint16 data_qual_id; /* validate and get udf data qualifier */ rv = _field_ft_group_keygen_param_udf_map_add(unit, keydata_keygen_md, param, custom_id, &data_qual_id, &index, &new_qual); BCM_IF_ERROR_RETURN(rv); *qual = (bcm_field_qualify_t) data_qual_id; if (new_qual == FALSE) { return BCM_E_NONE; } /* Add udf qual cfg to db */ rv = _field_ft_group_keygen_udf_qual_cfg_init(unit, qual_cfg_info_db, data_qual_id, keydata_keygen_md->param_udf_map[index].chunk_hw_bmap, &qual_width, &qual_cfg_parts); BCM_IF_ERROR_RETURN(rv); /* Derive qual flags from width and parts */ if (((qual_width == 16) && (qual_cfg_parts == 2)) || ((qual_width > 16) && (qual_cfg_parts > 2))) { *flags |= _FP_FT_TRACKING_PARAM_F_DATA_USE_GRAN8; } else if (qual_width > 16) { *flags |= _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32; } return rv; } /* * Function: * _field_ft_group_param_udf_qual_get * Purpose: * Get mapped data qualifier for given <param, custom>. * Parameters: * unit - (IN) BCM device number. * element_map- (IN) group tracking element map * Returns: */ STATIC int _field_ft_group_param_udf_qual_get(int unit, _field_ft_group_keydata_keygen_md_t *keydata_keygen_md, bcm_flowtracker_tracking_param_type_t param, uint16 custom_id, bcm_field_qualify_t *qual) { int idx; for (idx = 0; idx < keydata_keygen_md->num_udf_maps; idx++) { if ((keydata_keygen_md->param_udf_map[idx].param == param) && (keydata_keygen_md->param_udf_map[idx].custom_id == custom_id)) { break; } } if (idx == keydata_keygen_md->num_udf_maps) { return BCM_E_NOT_FOUND; } *qual = keydata_keygen_md->param_udf_map[idx].qual_id; return BCM_E_NONE; } /* * Function: * _field_ft_tracking_param_qual_map_init * Purpose: * Initializes group tracking element map * Parameters: * unit - (IN) BCM device number. * element_map- (IN) group tracking element map * Returns: */ STATIC void _field_ft_tracking_param_qual_map_init(int unit, _field_ft_tracking_param_qual_map_t *pq_map) { if (pq_map == NULL) { return; } sal_memset(pq_map, 0, sizeof(_field_ft_tracking_param_qual_map_t)); return; } /* * Function: * _field_ft_tracking_param_qual_map_insert * Purpose: * Insert tracking param-qual map to map database. * Parameters: * unit - (IN) BCM device number. * param - (IN) tracking param * pq_map - (IN) tracking param-qual map * map_db - (IN/OUT) param and qual Map database * Returns: * BCM_E_NONE */ STATIC int _field_ft_tracking_param_qual_map_insert(int unit, uint16 param, _field_ft_tracking_param_qual_map_t *pq_map, _field_ft_tracking_param_qual_map_db_t *map_db) { _field_ft_tracking_param_qual_map_t *temp_map = NULL; /* Validate input params. */ if ((pq_map == NULL) || (map_db == NULL) || (param >= _FIELD_FT_TRACKING_PARAM_MAX)) { return BCM_E_PARAM; } temp_map = map_db->param_qual_map[param]; if (temp_map == NULL) { _FP_XGS3_ALLOC(temp_map, sizeof(_field_ft_tracking_param_qual_map_t), "tracking param-qual map"); } else { return BCM_E_INTERNAL; } if (temp_map == NULL) { return BCM_E_MEMORY; } map_db->param_qual_map[param] = temp_map; sal_memcpy(temp_map, pq_map, sizeof(_field_ft_tracking_param_qual_map_t)); return BCM_E_NONE; } /* * Function: * _field_ft_tracking_param_qual_map_db_cleanup * Purpose: * Cleanup tracking param and qualifier map database * Parameters: * unit - (IN) BCM device number. * ft_info - (IN) Flowtracker specific info * Returns: * None. */ void _field_ft_tracking_param_qual_map_db_cleanup(int unit, _field_ft_info_t *ft_info) { uint16 param = 0; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; if ((ft_info == NULL) || (ft_info->param_qual_map_db == NULL)) { return; } map_db = ft_info->param_qual_map_db; for (param = 0; param < _FIELD_FT_TRACKING_PARAM_MAX; param++) { if (map_db->param_qual_map[param]) { sal_free(map_db->param_qual_map[param]); map_db->param_qual_map[param] = NULL; } } sal_free(map_db); ft_info->param_qual_map_db = NULL; } STATIC int _field_ft_stage_is_qual_supported(int unit, bcm_field_qualify_t qual, bcmi_keygen_qual_cfg_info_db_t *qual_cfg_info_db) { if (qual_cfg_info_db == NULL) { return FALSE; } if (qual_cfg_info_db->qual_cfg_info[qual] != NULL) { return TRUE; } return FALSE; } /* * Function: * _field_ft_tracking_param_qual_map_db_init * Purpose: * Initialize tracking params and qualifier map database * Parameters: * unit - (IN) BCM device number. * ft_info - (IN/OUT) Flowtracker info structure * Returns: * BCM_E_XXX */ int _field_ft_tracking_param_qual_map_db_init(int unit, _field_ft_info_t *ft_info, bcmi_keygen_qual_cfg_info_db_t *qual_cfg_info_db) { int rv = BCM_E_NONE; uint16 shift = 0; uint16 ft_type_bmp = 0; uint32 flags = 0; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _FP_FT_TRACKING_PARAM_QUAL_MAP_DECL; if (ft_info == NULL) { return BCM_E_PARAM; } _FP_XGS3_ALLOC(map_db, sizeof(_field_ft_tracking_param_qual_map_db_t), "tracking param qual map db"); if (map_db == NULL) { return BCM_E_MEMORY; } ft_info->param_qual_map_db = map_db; /* Tracking param qualifier map. */ ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeSrcIPv4, bcmFieldQualifySrcIp, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeDstIPv4, bcmFieldQualifyDstIp, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeSrcIPv6, bcmFieldQualifySrcIp6, 0, 128, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeDstIPv6, bcmFieldQualifyDstIp6, 0, 128, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeL4SrcPort, bcmFieldQualifyL4SrcPort, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeL4DstPort, bcmFieldQualifyL4DstPort, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIPProtocol, bcmFieldQualifyIpProtocol, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeVRF, bcmFieldQualifyVrf, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTTL, bcmFieldQualifyTtl, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIPLength, bcmFieldQualifyIp4Length, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTcpWindowSize, bcmFieldQualifyTcpWindowSize, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeL2ForwardingField, bcmFieldQualifyVpn, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeVxlanNetworkId, bcmFieldQualifyVxlanNetworkId, 0, 24, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeNextHeader, bcmFieldQualifyIp6PktNextHeader, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeHopLimit, bcmFieldQualifyIp6PktHopLimit, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeInnerSrcIPv4, bcmFieldQualifyInnerSrcIp, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeInnerDstIPv4, bcmFieldQualifyInnerDstIp, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerSrcIPv6, bcmFieldQualifyInnerSrcIp6, 0, 128, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerDstIPv6, bcmFieldQualifyInnerDstIp6, 0, 128, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerIPProtocol, bcmFieldQualifyInnerIpProtocol, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerTTL, bcmFieldQualifyInnerTtl, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerNextHeader, bcmFieldQualifyInnerIp6PktNextHeader, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerHopLimit, bcmFieldQualifyInnerIp6PktHopLimit, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerL4SrcPort, bcmFieldQualifyInnerL4SrcPort, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerL4DstPort, bcmFieldQualifyInnerL4DstPort, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTcpFlags, bcmFieldQualifyTcpControl, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerTcpFlags, bcmFieldQualifyInnerTcpControl, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeOuterVlanTag, bcmFieldQualifyOuterVlan, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIP6Length, bcmFieldQualifyIp6Length, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerIPLength, bcmFieldQualifyTunnelPayloadIp4Length, 0, 16, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeInnerIP6Length, bcmFieldQualifyTunnelPayloadIp6Length, 0, 16, ft_type_bmp); if (_field_ft_stage_is_qual_supported(unit, bcmFieldQualifyGbpSrcId, qual_cfg_info_db)) { ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeGbpSrcId, bcmFieldQualifyGbpSrcId, 0, 16, ft_type_bmp); } ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeTunnelClass, bcmFieldQualifyTunnelId, 0, 24, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPacketTos, bcmFieldQualifyTos, 0, 8, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_UDF_MAPPED, bcmFlowtrackerTrackingParamTypeTcpSeqNumber, 0, 0, 32, ft_type_bmp); /* Width unknown */ ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_UDF_MAPPED, bcmFlowtrackerTrackingParamTypeCustom, 0, 0, 0, ft_type_bmp); /* Tracking param which uses ALU32 */ flags = _FP_FT_TRACKING_PARAM_F_ALU32_REQ; ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeDosAttack, bcmFieldQualifyDosAttackEvents, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32, bcmFlowtrackerTrackingParamTypeInnerDosAttack, bcmFieldQualifyInnerDosAttackEvents, 0, 32, ft_type_bmp); /* Tracking param with no qualifier, used for counting */ flags |= _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT | BCMI_FT_TYPE_F_AMFT | BCMI_FT_TYPE_F_AEFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypePktCount, 0, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT | BCMI_FT_TYPE_F_AMFT | BCMI_FT_TYPE_F_AEFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeByteCount, 0, 0, 32, ft_type_bmp); /* Timestamp tracking parameters are not sent to FT group. */ flags = _FP_FT_TRACKING_PARAM_F_NO_FILL; flags |= _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampNewLearn, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampFlowStart, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampFlowEnd, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_MICRO); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampCheckEvent1, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_MICRO); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampCheckEvent2, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampIngress, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_EFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTimestampEgress, 0, 0, 0, ft_type_bmp); /* Map Tracking Params to ignore processing. */ flags = _FP_FT_TRACKING_PARAM_F_NO_FILL; flags |= _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; ft_type_bmp = (BCMI_FT_TYPE_F_ANY); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeNone, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_ANY); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeFlowtrackerCheck, 0, 0, 0, ft_type_bmp); /* Tracking ALU Data */ shift = _FP_FT_TRACKING_ALU_DATA_PARAM_MAP_START; flags = _FP_FT_TRACKING_PARAM_F_ALU_DATA; _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsFIN + shift, bcmFieldQualifyTcpControl, 0, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsSYN + shift, bcmFieldQualifyTcpControl, 1, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsRST + shift, bcmFieldQualifyTcpControl, 2, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsPSH + shift, bcmFieldQualifyTcpControl, 3, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsACK + shift, bcmFieldQualifyTcpControl, 4, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsURG + shift, bcmFieldQualifyTcpControl, 5, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsECE + shift, bcmFieldQualifyTcpControl, 6, 1, ft_type_bmp); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, _bcmFieldFtAluDataTcpFlagsCWR + shift, bcmFieldQualifyTcpControl, 7, 1, ft_type_bmp); #ifdef BCM_FLOWTRACKER_V2_SUPPORT /* Add MFT/EFT tracking params in db */ if (soc_feature(unit, soc_feature_flex_flowtracker_ver_2)) { flags = _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; /* Enable chip and end-to-end delay tracking only if * feature is enabled which in turn is set based on * OTP bit (LATENCY_TRACKING_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_chip_e2e_delay)) { ft_type_bmp = (BCMI_FT_TYPE_F_EFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeChipDelay, 0, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeE2EDelay, 0, 0, 32, ft_type_bmp); } /* Enable inter packet arrival and departure delay tracking only * if feature is enabled which in turn is set based on * OTP bit (IAT_IDT_TRACKING_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_iat_idt_delay)) { ft_type_bmp = (BCMI_FT_TYPE_F_IFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeIPATDelay, 0, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_EFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeIPDTDelay, 0, 0, 32, ft_type_bmp); } ft_type_bmp = (BCMI_FT_TYPE_F_MICRO); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_NO_FILL, bcmFlowtrackerTrackingParamTypeTimestampCheckEvent3, 0, 0, 0, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_MICRO); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_NO_FILL, bcmFlowtrackerTrackingParamTypeTimestampCheckEvent4, 0, 0, 0, ft_type_bmp); /* Enable alu delay computation only if feature * is enabled which in turn is set based on * OTP bit (ALU_LATENCY_SUPPORT_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_alu_delay)) { ft_type_bmp = (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeIngressDelay, 0, 0, 32, ft_type_bmp); ft_type_bmp = (BCMI_FT_TYPE_F_EFT | BCMI_FT_TYPE_F_AEFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags | _FP_FT_TRACKING_PARAM_F_ALU32_REQ, bcmFlowtrackerTrackingParamTypeEgressDelay, 0, 0, 32, ft_type_bmp); } /* MMU Tracking Params */ rv = _field_ft_mmu_tracking_param_qual_map_db_init(unit, map_db); BCMI_IF_ERROR_CLEANUP(rv); /* Egress Tracking Params */ rv = _field_ft_egr_tracking_param_qual_map_db_init(unit, map_db); BCMI_IF_ERROR_CLEANUP(rv); } #endif cleanup: if (rv != BCM_E_NONE) { (void) _field_ft_tracking_param_qual_map_db_cleanup(unit, ft_info); } return rv; } /* Alu Data info For Outer TCP Control */ static _field_ft_tracking_alu_data_info_t _field_ft_alu_data_info_tcp_control[] = { {_bcmFieldFtAluDataTcpFlagsFIN, bcmFieldQualifyTcpControl, 0, 1, 2}, {_bcmFieldFtAluDataTcpFlagsSYN, bcmFieldQualifyTcpControl, 1, 1, 0}, {_bcmFieldFtAluDataTcpFlagsRST, bcmFieldQualifyTcpControl, 2, 1, 3}, {_bcmFieldFtAluDataTcpFlagsPSH, bcmFieldQualifyTcpControl, 3, 1, 4}, {_bcmFieldFtAluDataTcpFlagsACK, bcmFieldQualifyTcpControl, 4, 1, 1}, {_bcmFieldFtAluDataTcpFlagsURG, bcmFieldQualifyTcpControl, 5, 1, 5}, {_bcmFieldFtAluDataTcpFlagsECE, bcmFieldQualifyTcpControl, 6, 1, 6}, {_bcmFieldFtAluDataTcpFlagsCWR, bcmFieldQualifyTcpControl, 7, 1, 7} }; /* Alu Data info for Inner TCP Control */ static _field_ft_tracking_alu_data_info_t _field_ft_alu_data_info_inner_tcp_control[] = { {_bcmFieldFtAluDataTcpFlagsFIN, bcmFieldQualifyInnerTcpControl, 0, 1, 2}, {_bcmFieldFtAluDataTcpFlagsSYN, bcmFieldQualifyInnerTcpControl, 1, 1, 0}, {_bcmFieldFtAluDataTcpFlagsRST, bcmFieldQualifyInnerTcpControl, 2, 1, 3}, {_bcmFieldFtAluDataTcpFlagsPSH, bcmFieldQualifyInnerTcpControl, 3, 1, 4}, {_bcmFieldFtAluDataTcpFlagsACK, bcmFieldQualifyInnerTcpControl, 4, 1, 1}, {_bcmFieldFtAluDataTcpFlagsURG, bcmFieldQualifyInnerTcpControl, 5, 1, 5}, {_bcmFieldFtAluDataTcpFlagsECE, bcmFieldQualifyInnerTcpControl, 6, 1, 6}, {_bcmFieldFtAluDataTcpFlagsCWR, bcmFieldQualifyInnerTcpControl, 7, 1, 7} }; /* * Function: * _field_hx5_ftg_alu_data_info_get * Purpose: * Get pointer to ALU Data info * Parameters: * unit - (IN) BCM device number. * id - (IN) flowtracker group id. * info - (OUT) Pointer to ALU Data Info. * num_info - (OUT) number of ALU Data info. * Returns: * BCM_E_NONE * Notes: * ALU Data info is fixed to extract TCP Flags. * If ALU data needs to be extracted from other source * flowtracker group need to convey it. * This function set the pointer to fixed ALU Data info * and no memory allocated is required for now. */ STATIC int _field_hx5_ftg_alu_data_info_get(int unit, bcm_flowtracker_group_t id, _field_ft_tracking_alu_data_info_t **info, int *num_info) { int rv = BCM_E_NONE; int alu_data_info_count = 0; bcm_flowtracker_state_transition_type_t st_type; _field_ft_tracking_alu_data_info_t *alu_data_info = NULL; rv = bcmi_esw_ft_group_state_transition_type_get(unit, id, &st_type); BCM_IF_ERROR_RETURN(rv); switch(st_type) { case bcmFlowtrackerStateTransitionTypeTcpControl: alu_data_info = _field_ft_alu_data_info_tcp_control; alu_data_info_count = COUNTOF(_field_ft_alu_data_info_tcp_control); break; case bcmFlowtrackerStateTransitionTypeInnerTcpControl: alu_data_info = _field_ft_alu_data_info_inner_tcp_control; alu_data_info_count = COUNTOF(_field_ft_alu_data_info_inner_tcp_control); break; default: return BCM_E_PARAM; } if (num_info != NULL) { *num_info = alu_data_info_count; } if (info != NULL) { *info = alu_data_info; } return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_cfg_qual_alloc * Purpose: * Allocate memory for qual_info_arr for session key and * session data. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (IN) Ft group Keygen metadata * Returns: * None. */ STATIC int _field_hx5_ftg_keygen_cfg_qual_alloc(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int num_key_params = 0; int num_data_params = 0; int num_tracking_params = 0; int num_flowchecks = 0; int total_data_quals = 0; int num_alu_data = 0; bcm_field_qualify_t qual; bcm_field_qset_t qset; bcm_flowtracker_tracking_param_info_t *tracking_param_info = NULL; _field_ft_tracking_alu_data_info_t *alu_data_info = NULL; bcmi_keygen_qual_info_t *qual_info_arr = NULL; if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } num_tracking_params = ftg_keygen_md->num_tracking_params; num_flowchecks = ftg_keygen_md->num_flowchecks; num_alu_data = ftg_keygen_md->num_alu_data; /* Calculate number of keys and data */ for (idx = 0; idx < num_tracking_params; idx++) { tracking_param_info = &ftg_keygen_md->tracking_params_info[idx]; if (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY) { num_key_params++; } else { num_data_params++; } } /* Validate number of key and data */ if (ftg_keygen_md->flags & _FIELD_FTG_KEYGEN_F_KEY_REQ) { if (num_key_params == 0) { LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "FT Group=%d - Tracking Key and/or" " Data not specified\n\r"), ftg_keygen_md->ft_group_id)); return BCM_E_CONFIG; } } if (ftg_keygen_md->flags & _FIELD_FTG_KEYGEN_F_DATA_REQ) { if (num_data_params == 0) { LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "FT Group=%d - Tracking Key and/or" " Data not specified\n\r"), ftg_keygen_md->ft_group_id)); return BCM_E_CONFIG; } } /* Calculate number of session data qualifiers */ total_data_quals = 0; /* Qualifiers for ALU Data */ BCM_FIELD_QSET_INIT(qset); for (idx = 0; idx < num_alu_data; idx++) { alu_data_info = &ftg_keygen_md->alu_data_info[idx]; qual = alu_data_info->qual; if (!(BCM_FIELD_QSET_TEST(qset, qual))) { total_data_quals++; BCM_FIELD_QSET_ADD(qset, qual); } } /* * Qualifiers in Flowtracker checks * Primary flowcheck can have action params also. * So, need to allocate memory for them too. */ total_data_quals += (2 * num_flowchecks); /* Qualifiers in Tracking params fo session data */ total_data_quals += num_data_params; /* Allocate qual_info_arr for session Key */ _FP_XGS3_ALLOC(qual_info_arr, num_key_params * sizeof(bcmi_keygen_qual_info_t), "skey qual info arr"); if (qual_info_arr == NULL) { rv = BCM_E_MEMORY; } else { ftg_keygen_md->skey_keygen_md.qual_info_arr = qual_info_arr; ftg_keygen_md->skey_keygen_md.max_qual_info_alloc = num_key_params; } /* Allocate qual_info_arr for session Data */ if (BCM_SUCCESS(rv)) { qual_info_arr = NULL; _FP_XGS3_ALLOC(qual_info_arr, total_data_quals * sizeof(bcmi_keygen_qual_info_t), "sdata qual info arr"); if (qual_info_arr == NULL) { rv = BCM_E_MEMORY; } else { ftg_keygen_md->sdata_keygen_md.qual_info_arr = qual_info_arr; ftg_keygen_md->sdata_keygen_md.max_qual_info_alloc = total_data_quals; } } return rv; } /* * Function: * _field_hx5_ftg_qual_ext_hw_info_get * Purpose: * Convert keygen_oper to qual_ext_offset_info and ext_codes. * Parameters: * unit - (IN) BCM device number. * key_or_data - (IN) Conversion of session key or data. * ftg_keygen_md - (IN) FT Group Keygen metadata. * qual_ext_offset_info - (OUT) Pointer to qual-extractor info. * ext_codes - (OUT) Pointer to extraction codes. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_qual_ext_hw_info_get(int unit, int key_or_data, _field_ft_group_keygen_md_t *ftg_keygen_md, _field_ft_qual_ext_offset_info_t **qual_ext_offset_info, _field_ft_keygen_ext_codes_t *ext_codes) { int rv = BCM_E_NONE; int keygen_profile = 0; int num_keygen_parts = 0; uint16 ext_ctrl_sel_info_count = 0; bcmi_keygen_oper_t *keygen_oper = NULL; bcmi_keygen_ext_ctrl_sel_info_t *ext_ctrl_sel_info = NULL; if ((ftg_keygen_md == NULL) || (ext_codes == NULL) || (qual_ext_offset_info == NULL)) { return BCM_E_PARAM; } if (key_or_data == 1) { keygen_oper = &ftg_keygen_md->skey_keygen_md.keygen_oper; num_keygen_parts = ftg_keygen_md->skey_keygen_md.num_parts; keygen_profile = _BCM_FIELD_FT_KEYGEN_PROFILE_AAB; } else { keygen_oper = &ftg_keygen_md->sdata_keygen_md.keygen_oper; num_keygen_parts = ftg_keygen_md->sdata_keygen_md.num_parts; keygen_profile = _BCM_FIELD_FT_KEYGEN_PROFILE_AB; } /* Get qual_ext_offset_info */ ext_ctrl_sel_info = keygen_oper->ext_ctrl_sel_info; ext_ctrl_sel_info_count = keygen_oper->ext_ctrl_sel_info_count; /* Dump Qualifiers and Extractors info from Keygen_oper */ LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "FT Group=%d Keygen Info for %s\r\n"), ftg_keygen_md->ft_group_id, ((key_or_data == 1) ? "SESSION KEY" : "SESSION DATA"))); (void) _bcm_field_keygen_qual_offset_info_dump(unit, num_keygen_parts, keygen_oper); (void) _bcm_field_ft_keygen_extractors_init(ext_codes); rv = _bcm_field_hx5_ft_keygen_extractors_set(unit, keygen_profile, ext_ctrl_sel_info_count, ext_ctrl_sel_info, ext_codes); BCMI_IF_ERROR_CLEANUP(rv); /* Process extracted qualifiers and extractors */ if (ext_ctrl_sel_info != NULL) { rv = _field_hx5_ft_qual_ext_offset_info_get(unit, num_keygen_parts, keygen_oper, qual_ext_offset_info); BCMI_IF_ERROR_CLEANUP(rv); /* Update Mask of extractors */ rv = _bcm_field_hx5_ft_keygen_extractors_mask_set(unit, *qual_ext_offset_info, ext_codes); BCMI_IF_ERROR_CLEANUP(rv); rv = _field_hx5_ft_qual_offset_ext_shift_apply(unit, 0, ext_codes, *qual_ext_offset_info); BCMI_IF_ERROR_CLEANUP(rv); } /* Dump Hardware Extraction codes */ (void) _bcm_field_hx5_ft_keygen_hw_extractors_dump(unit, ext_codes); cleanup: if (BCM_FAILURE(rv)) { if (*qual_ext_offset_info != NULL) { sal_free(*qual_ext_offset_info); *qual_ext_offset_info = NULL; } } return rv; } /* * Function: * _field_hx5_ftg_qual_offset_width_get * Purpose: * Get start and width from offset_arr for a qualifier. * Parameters: * unit - (IN) BCM device number. * offset_arr - (IN) Offset arr. * start_bit - (OUT) Start bit position. * width - (OUT) Number of bits. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_qual_offset_width_get(int unit, bcmi_keygen_qual_offset_t *offset_arr, int *start_bit, int *width) { int offset = 0; int part_width = 0; int total_width = 0; int num_offsets = 0; for (offset = 0; offset < BCMI_KEYGEN_QUAL_OFFSETS_MAX; offset++) { part_width = offset_arr->width[offset]; if (!part_width) { continue; } total_width += part_width; num_offsets += 1; if (num_offsets == offset_arr->num_offsets) { break; } } *start_bit = offset_arr->offset[0]; /* Make width multiple of 8 */ if ((total_width % 8) != 0) { *width = ((total_width + 8) / 8) * 8; } else { *width = total_width; } return BCM_E_NONE; } #ifdef BCM_FLOWTRACKER_V2_SUPPORT STATIC int _field_ftv2_ftg_vfp_opaqueid2_get(int unit, bcm_flowtracker_group_t id, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int q_idx = 0; int start_bit = 0, width = 0; _field_ft_keygen_ext_codes_t ext_codes; _field_ft_qual_ext_offset_info_t *qual_ext_offset_info = NULL; rv = _field_hx5_ftg_qual_ext_hw_info_get(unit, 0, ftg_keygen_md, &qual_ext_offset_info, &ext_codes); BCM_IF_ERROR_RETURN(rv); if (qual_ext_offset_info != NULL) { for (q_idx = 0; q_idx < qual_ext_offset_info->size; q_idx++) { if (qual_ext_offset_info->qid_arr[q_idx] != bcmFieldQualifyOpaqueObject2) { continue; } rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[q_idx], &start_bit, &width); BCM_IF_ERROR_RETURN(rv); } BCMI_FT_GROUP_EXT_HW_INFO_VFP_OPAQUEID2_START_BIT(unit, id) = start_bit; } return rv; } #endif /* * Function: * _field_hx5_ftg_keygen_oper_dump * Purpose: * Dump session key/data extraction information. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC void _field_hx5_ftg_keygen_oper_dump(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { uint32 idx = 0; bcmi_ft_group_alu_info_t *keydata_info = NULL; _field_ft_group_keygen_oper_info_t *oper_info = NULL; oper_info = &ftg_keygen_md->keydata_oper_info; LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "===Extraction Operation Info===\r\n"))); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "---Session Keys---\r\n"))); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, " Session Key Mode = %d\r\n"), oper_info->mode)); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, " Number of Session Keys = %d\r\n"), oper_info->num_skey_info)); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5s |%10s |%10s |%10s |\r\n"), "Idx", "Element", "Offset", "Length")); for (idx = 0; idx < oper_info->num_skey_info; idx++) { keydata_info = &oper_info->skey_info[idx]; LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5d |%10d |%10d |%10d |\r\n"), idx, keydata_info->element_type1, keydata_info->key1.location, keydata_info->key1.length)); } LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "---Session Data---\r\n"))); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, " Number of Session Data = %d\r\n"), oper_info->num_sdata_info)); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5s |%10s |%10s |"), "Idx", "FlowCheck", "Type")); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "%10s |%10s |%10s |%10s |\r\n"), "Element", "Offset", "Length", "ALU Req")); for (idx = 0; idx < oper_info->num_sdata_info; idx++) { keydata_info = &oper_info->sdata_info[idx]; LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5d |%10x |%10s |"), idx, keydata_info->flowchecker_id, "Primary")); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "%10d |" "%10d |%10d |%10d |\r\n"), keydata_info->element_type1, keydata_info->key1.location, keydata_info->key1.length, keydata_info->key1.is_alu)); /* Print secondary and Action key */ if (keydata_info->flowchecker_id != 0) { if (keydata_info->action_element_type != bcmFlowtrackerTrackingParamTypeNone) { LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5d |%10x |%10s |"), idx, keydata_info->flowchecker_id, "Action")); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "%10d |" "%10d |%10d |%10d |\r\n"), keydata_info->action_element_type, keydata_info->action_key.location, keydata_info->action_key.length, keydata_info->key1.is_alu)); } if (keydata_info->element_type2 != bcmFlowtrackerTrackingParamTypeNone) { LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "|%5d |%10x |%10s |"), idx, BCMI_FT_FLOWCHECKER_INDEX_SET(keydata_info->flowchecker_id, BCM_FT_IDX_TYPE_2ND_CHECK), "Second")); LOG_VERBOSE(BSL_LS_BCM_FP, (BSL_META_U(unit, "%10d |" "%10d |%10d |%10d |\r\n"), keydata_info->element_type2, keydata_info->key2.location, keydata_info->key2.length, keydata_info->key2.is_alu)); } } } } /* * Function: * _field_hx5_ftg_keygen_initialize * Purpose: * Initialize ft group keygen metadata struct. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_initialize(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; _field_stage_t *stage_fc = NULL; bcm_flowtracker_group_type_t group_type; if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } /* Validate Flowtracker group */ rv = bcmi_ft_group_is_invalid(unit, ftg_keygen_md->ft_group_id); /* Get Flowtracker Stage info */ if (BCM_SUCCESS(rv)) { rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); } if (BCM_SUCCESS(rv)) { /* Ft info from stage */ ftg_keygen_md->ft_info = stage_fc->ft_info; } group_type = BCMI_FT_GROUP_TYPE_GET(ftg_keygen_md->ft_group_id); ftg_keygen_md->ft_type_bmp = 0; if (group_type == bcmFlowtrackerGroupTypeNone) { ftg_keygen_md->ft_type_bmp = BCMI_FT_TYPE_F_MICRO; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_KEY_REQ; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_DATA_REQ; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_ALU_DATA_REQ; } else if (group_type == bcmFlowtrackerGroupTypeAggregateIngress) { ftg_keygen_md->ft_type_bmp = BCMI_FT_TYPE_F_AIFT; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_DATA_REQ; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_ALU_DATA_REQ; } else if (group_type == bcmFlowtrackerGroupTypeAggregateMmu) { ftg_keygen_md->ft_type_bmp = BCMI_FT_TYPE_F_AMFT; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_DATA_REQ; } else if (group_type == bcmFlowtrackerGroupTypeAggregateEgress) { ftg_keygen_md->ft_type_bmp = BCMI_FT_TYPE_F_AEFT; ftg_keygen_md->flags |= _FIELD_FTG_KEYGEN_F_DATA_REQ; } /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_ALLOC; } return rv; } /* * Function: * _field_hx5_ftg_keygen_cfg_alloc * Purpose: * Read FT group tracking param and flowchecks info and allocate * memories to qual_info_arr for input to Keygen algo. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_alloc(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int num_tracking_params = 0; int num_flowchecks = 0; bcm_flowtracker_group_t ft_group_id; ftg_keygen_md->prev_state = ftg_keygen_md->state; ft_group_id = ftg_keygen_md->ft_group_id; /* Get number of tracking params from group template */ rv = bcm_esw_flowtracker_group_tracking_params_get(unit, ft_group_id, 0, NULL, &num_tracking_params); /* Get number of flowcheck info from flowtracker group */ if (BCM_SUCCESS(rv)) { rv = bcmi_flowtracker_check_get_all(unit, ft_group_id, 0, 0, NULL, &num_flowchecks); } /* Allocate memory for tracking params info */ if (BCM_SUCCESS(rv)) { ftg_keygen_md->num_tracking_params = num_tracking_params; _FP_XGS3_ALLOC(ftg_keygen_md->tracking_params_info, num_tracking_params * sizeof(bcm_flowtracker_tracking_param_info_t), "tracking params info"); if (ftg_keygen_md->tracking_params_info == NULL) { rv = BCM_E_MEMORY; } } /* Allocate memory for flowchecks */ if (BCM_SUCCESS(rv)) { ftg_keygen_md->num_flowchecks = num_flowchecks; _FP_XGS3_ALLOC(ftg_keygen_md->flowtracker_checks, num_flowchecks * sizeof(bcm_flowtracker_check_t), "flowtracker checks"); if (ftg_keygen_md->flowtracker_checks == NULL) { rv = BCM_E_MEMORY; } } /* Read tracking params info */ if (BCM_SUCCESS(rv)) { rv = bcm_esw_flowtracker_group_tracking_params_get(unit, ft_group_id, num_tracking_params, &ftg_keygen_md->tracking_params_info[0], &num_tracking_params); } /* Read flowtracker checks */ if (BCM_SUCCESS(rv)) { rv = bcmi_flowtracker_check_get_all(unit, ft_group_id, 0, num_flowchecks, &ftg_keygen_md->flowtracker_checks[0], &num_flowchecks); } /* Read ALU Data */ if (BCM_SUCCESS(rv) && (ftg_keygen_md->flags & _FIELD_FTG_KEYGEN_F_ALU_DATA_REQ)) { rv = _field_hx5_ftg_alu_data_info_get(unit, ft_group_id, &ftg_keygen_md->alu_data_info, &ftg_keygen_md->num_alu_data); } /* Allocate memory for qual_info arr of session key/Data */ if (BCM_SUCCESS(rv)) { rv = _field_hx5_ftg_keygen_cfg_qual_alloc(unit, ftg_keygen_md); } /* Move to next state */ ftg_keygen_md->state_rv = rv; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_ALU_QUAL_ADD; } return rv; } /* * Function: * _field_hx5_ftg_keygen_cfg_alu_qual_add * Purpose: * Read FT group Alu data info and populate qual_info_arr * for session data extraction. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Added logic to skip alu param extraction for non IFT stage. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_alu_qual_add(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int new_idx = 0; int idx = 0; bcm_field_qualify_t qual; uint16 allocated_quals = 0; bcmi_keygen_qual_info_t *qual_info_arr = NULL; _field_ft_group_keydata_keygen_md_t *sdata_keygen_md = NULL; _field_ft_tracking_alu_data_info_t *alu_data_info = NULL; /* Check if ALU data is required */ if (ftg_keygen_md->num_alu_data == 0) { goto cleanup; } ftg_keygen_md->prev_state = ftg_keygen_md->state; /* Add to Session Data qual_info_arr */ sdata_keygen_md = &ftg_keygen_md->sdata_keygen_md; allocated_quals = sdata_keygen_md->qual_info_count; qual_info_arr = sdata_keygen_md->qual_info_arr; for (idx = 0; idx < ftg_keygen_md->num_alu_data; idx++) { alu_data_info = &ftg_keygen_md->alu_data_info[idx]; qual = alu_data_info->qual; /* Skip if it is previously added */ if (BCM_FIELD_QSET_TEST(sdata_keygen_md->qset, qual)) { continue; } new_idx = allocated_quals; qual_info_arr[new_idx].qual_id = qual; qual_info_arr[new_idx].flags = BCMI_KEYGEN_QUAL_F_STICKY_CONTAINERS | BCMI_KEYGEN_QUAL_F_USE_FINFO_NEW | BCMI_KEYGEN_QUAL_F_USE_L2_EXT_GRAN16; allocated_quals++; BCM_FIELD_QSET_ADD(sdata_keygen_md->qset, qual); } sdata_keygen_md->qual_info_count = allocated_quals; cleanup: /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_FC_QUAL_ADD; return rv; } STATIC int _field_ft_keygen_qual_info_flags_set(int unit, int is_key, uint32 param_qual_flags, uint32 udf_qual_flags, uint32 *qual_info_flags) { (*qual_info_flags) = BCMI_KEYGEN_QUAL_F_STICKY_CONTAINERS; if (is_key) { (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_USE_L2_EXT_GRAN8; (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_USE_L2_EXT_GRAN16; } else { (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_USE_FINFO_NEW; (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_USE_L2_EXT_GRAN16; if ((param_qual_flags & _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32) || (udf_qual_flags & _FP_FT_TRACKING_PARAM_F_DATA_MODULO_32)) { (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_EXTRACT_TO_MODULO_32_OFFSET; } if (udf_qual_flags & _FP_FT_TRACKING_PARAM_F_DATA_USE_GRAN8) { (*qual_info_flags) |= BCMI_KEYGEN_QUAL_F_USE_L2_EXT_GRAN8; } } return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_cfg_flowcheck_qual_add * Purpose: * Read FT group Flowcheck info and populate qual_info_arr * for session data extraction. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Tracking Params which belongs to MFT/EFT stage does not need * extraction hence skipped while adding in qual extraction db. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_flowcheck_qual_add(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int p_idx = 0; int new_idx = 0; int num_params = 0; int num_operands = 0; uint16 param; uint16 param_list[2]; uint16 custom_id_list[2]; uint16 chk_ft_type_bmp = 0; uint16 ext_ft_type_flag = 0; uint16 allocated_quals = 0; uint32 udf_qual_flags = 0; bcm_field_qualify_t qual; bcm_flowtracker_check_t check_id; bcm_flowtracker_check_info_t fc_info; bcmi_keygen_qual_info_t *qual_info_arr = NULL; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _field_ft_group_keydata_keygen_md_t *sdata_keygen_md = NULL; bcm_flowtracker_check_action_info_t action_info; /* validate inputs */ if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } /* Check if Flowcheck is required */ if (ftg_keygen_md->num_flowchecks == 0) { goto cleanup; } ftg_keygen_md->prev_state = ftg_keygen_md->state; map_db = ftg_keygen_md->ft_info->param_qual_map_db; /* Add to Session Data qual_info_arr */ sdata_keygen_md = &ftg_keygen_md->sdata_keygen_md; allocated_quals = sdata_keygen_md->qual_info_count; qual_info_arr = sdata_keygen_md->qual_info_arr; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_IFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_IFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AIFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_AIFT; } for (idx = 0; idx < ftg_keygen_md->num_flowchecks; idx++) { num_params = 0; check_id = ftg_keygen_md->flowtracker_checks[idx]; sal_memset(&fc_info, 0, sizeof(bcm_flowtracker_check_info_t)); rv = bcmi_ft_check_get(unit, check_id, &fc_info, &chk_ft_type_bmp); if (BCM_FAILURE(rv)) { goto cleanup; } /* Check must belong to only ft_type */ if (!BCMI_FT_TYPE_F_IS_UNIQUE(chk_ft_type_bmp & ext_ft_type_flag)) { return BCM_E_INTERNAL; } /* Extracting only if checkers ft types match */ if (!(chk_ft_type_bmp & ext_ft_type_flag)) { continue; } param_list[0] = fc_info.param; custom_id_list[0] = fc_info.custom_id; num_params++; /* If primary flowcheck, get action info */ if (BCMI_FT_IDX_IS_PRIMARY_CHECK(check_id)) { bcm_flowtracker_check_action_info_t_init(&action_info); rv = bcm_esw_flowtracker_check_action_info_get(unit, check_id, &action_info); BCMI_IF_ERROR_CLEANUP(rv); /* If Action does not requires param, continue */ rv = bcmi_esw_ft_check_action_num_operands_get(unit, action_info.action, &num_operands); BCM_IF_ERROR_CLEANUP(rv); if (num_operands != 0) { param_list[1] = action_info.param; custom_id_list[1] = action_info.custom_id; num_params++; } } for (p_idx = 0; p_idx < num_params; p_idx++) { param = param_list[p_idx]; pq_map = map_db->param_qual_map[param]; if ((param > _FIELD_FT_TRACKING_PARAM_MAX) || (pq_map == NULL)) { rv = BCM_E_PARAM; BCMI_IF_ERROR_CLEANUP(rv); } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED) { continue; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = _field_ft_group_param_udf_qual_init(unit, ftg_keygen_md->ft_info->flow_data_qual_cfg, sdata_keygen_md, param, custom_id_list[p_idx], &qual, &udf_qual_flags); BCMI_IF_ERROR_CLEANUP(rv); } else { udf_qual_flags = 0; qual = pq_map->qual; } if (!BCM_FIELD_QSET_TEST(sdata_keygen_md->qset, qual)) { new_idx = allocated_quals; qual_info_arr[new_idx].qual_id = qual; _field_ft_keygen_qual_info_flags_set(unit, 0, pq_map->flags, udf_qual_flags, &qual_info_arr[new_idx].flags); allocated_quals++; BCM_FIELD_QSET_ADD(sdata_keygen_md->qset, qual); } } } sdata_keygen_md->qual_info_count = allocated_quals; cleanup: /* Move to next state */ ftg_keygen_md->state_rv = rv; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_DATA_KEY_QUAL_ADD; } return rv; } /* * Function: * _field_hx5_ftg_keygen_cfg_data_key_qual_add * Purpose: * Read FT group Tracking param info and populate qual_info_arr * for session key and session data extraction. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Tracking Params which belongs to MFT/EFT stage does not need * extraction hence skipped while adding in qual extraction db. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_data_key_qual_add(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; uint16 param; int new_idx = 0; int is_key = FALSE; bcm_field_qualify_t qual; int num_tracking_params = 0; uint16 ext_ft_type_flag = 0; uint16 *allocated_quals = NULL; uint16 *qual_param_idx_arr = NULL; uint32 udf_qual_flags = 0; bcmi_keygen_qual_info_t *qual_info_arr = NULL; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _field_ft_group_keydata_keygen_md_t *skey_keygen_md = NULL; _field_ft_group_keydata_keygen_md_t *sdata_keygen_md = NULL; bcm_flowtracker_tracking_param_info_t *tracking_param_info = NULL; map_db = ftg_keygen_md->ft_info->param_qual_map_db; num_tracking_params = ftg_keygen_md->num_tracking_params; skey_keygen_md = &ftg_keygen_md->skey_keygen_md; sdata_keygen_md = &ftg_keygen_md->sdata_keygen_md; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_IFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_IFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AIFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_AIFT; } /* Loop through tracking params */ for (idx = 0; idx < num_tracking_params; idx++) { tracking_param_info = &ftg_keygen_md->tracking_params_info[idx]; if (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY) { is_key = TRUE; qual_info_arr = skey_keygen_md->qual_info_arr; allocated_quals = &skey_keygen_md->qual_info_count; qual_param_idx_arr = &skey_keygen_md->qual_param_idx_arr[0]; } else { is_key = FALSE; qual_info_arr = sdata_keygen_md->qual_info_arr; allocated_quals = &sdata_keygen_md->qual_info_count; qual_param_idx_arr = &sdata_keygen_md->qual_param_idx_arr[0]; } /* Handling tracking param FlowtrackerCheck */ if (tracking_param_info->param == bcmFlowtrackerTrackingParamTypeFlowtrackerCheck) { rv = bcmi_ft_group_check_validate(unit, BCMI_FT_GROUP_CHECK_MATCH_GROUP, ftg_keygen_md->ft_group_id, tracking_param_info->check_id); if ((rv != BCM_E_NONE) || (is_key == TRUE)) { rv = BCM_E_PARAM; BCMI_IF_ERROR_CLEANUP(rv); } } param = tracking_param_info->param; pq_map = map_db->param_qual_map[param]; if ((param > _FIELD_FT_TRACKING_PARAM_MAX) || (pq_map == NULL)) { rv = BCM_E_PARAM; BCMI_IF_ERROR_CLEANUP(rv); } /* Skip non IFT/AIFT qualifiers */ if (!(pq_map->db_ft_type_bmp & ext_ft_type_flag)) { continue; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { if (is_key == TRUE) { rv = _field_ft_group_param_udf_qual_init(unit, ftg_keygen_md->ft_info->flow_key_qual_cfg, skey_keygen_md, param, tracking_param_info->custom_id, &qual, &udf_qual_flags); } else { rv = _field_ft_group_param_udf_qual_init(unit, ftg_keygen_md->ft_info->flow_data_qual_cfg, sdata_keygen_md, param, tracking_param_info->custom_id, &qual, &udf_qual_flags); } BCMI_IF_ERROR_CLEANUP(rv); } else { udf_qual_flags = 0; qual = pq_map->qual; } /* Skip non mapped qualifiers */ if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED) { if ((soc_feature(unit, soc_feature_flowtracker_ts_64_sw_war_support)) && ((param == bcmFlowtrackerTrackingParamTypeTimestampNewLearn) || (param == bcmFlowtrackerTrackingParamTypeTimestampFlowStart) || (param == bcmFlowtrackerTrackingParamTypeTimestampFlowEnd) || (param == bcmFlowtrackerTrackingParamTypeTimestampCheckEvent1) || (param == bcmFlowtrackerTrackingParamTypeTimestampCheckEvent2) || (param == bcmFlowtrackerTrackingParamTypeTimestampCheckEvent3) || (param == bcmFlowtrackerTrackingParamTypeTimestampCheckEvent4)) && ((tracking_param_info->src_ts == bcmFlowtrackerTimestampSourceNTP) || (tracking_param_info->src_ts == bcmFlowtrackerTimestampSourcePTP))) { qual = bcmFieldQualifyOpaqueObject2; } else { continue; } } if (((is_key == TRUE) && BCM_FIELD_QSET_TEST(skey_keygen_md->qset, qual)) || ((is_key == FALSE) && BCM_FIELD_QSET_TEST(sdata_keygen_md->qset, qual))) { continue; } new_idx = *allocated_quals; qual_info_arr[new_idx].qual_id = qual; _field_ft_keygen_qual_info_flags_set(unit, is_key, pq_map->flags, udf_qual_flags, &qual_info_arr[new_idx].flags); if (is_key == TRUE) { qual_param_idx_arr[new_idx] = idx; } (*allocated_quals)++; if (is_key == TRUE) { BCM_FIELD_QSET_ADD(skey_keygen_md->qset, qual); } else { BCM_FIELD_QSET_ADD(sdata_keygen_md->qset, qual); } } cleanup: ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_DATA_QUAL_ADJUST; } return rv; } /* * Function: * _field_hx5_ftg_keygen_qual_info_shift * Purpose: * Shift qual info in qual_info_arr downward. * Parameters: * unit - (IN) BCM device number. * start_idx - (IN) Start index (lower number) * end_idx - (IN) End Index (higher number) * qual_info_arr - (IN/OUT) Qual info array. * qual_size_arr - (IN/OUT) Qual size array. * Returns: * BCM_E_XXX */ int _field_hx5_ftg_keygen_qual_info_shift(int unit, int start_idx, int end_idx, bcmi_keygen_qual_info_t *qual_info_arr, uint16 *qual_size_arr, uint16 *qual_param_idx_arr) { int idx = 0; uint16 p_idx = 0, qual_size = 0; bcmi_keygen_qual_info_t temp_qual_info; qual_size = qual_size_arr[end_idx]; p_idx = qual_param_idx_arr[end_idx]; sal_memcpy(&temp_qual_info, &qual_info_arr[end_idx], sizeof(bcmi_keygen_qual_info_t)); for (idx = end_idx; idx > start_idx; idx--) { qual_size_arr[idx] = qual_size_arr[idx - 1]; qual_param_idx_arr[idx] = qual_param_idx_arr[idx - 1]; sal_memcpy(&qual_info_arr[idx], &qual_info_arr[idx - 1], sizeof(bcmi_keygen_qual_info_t)); } qual_size_arr[start_idx] = qual_size; qual_param_idx_arr[start_idx] = p_idx; sal_memcpy(&qual_info_arr[start_idx], &temp_qual_info, sizeof(bcmi_keygen_qual_info_t)); return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_cfg_data_qual_adjust * Purpose: * Re-arrange, if required, qual_info_arr for session data extraction. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_data_qual_adjust(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int rank1_idx = 0; uint16 qual_size = 0; uint16 qual_info_count = 0; uint16 qual_size_arr[20]; bcmi_keygen_cfg_t keygen_cfg; _field_ft_info_t *ft_info = NULL; bcmi_keygen_qual_info_t *qual_info_arr = NULL; uint16 *qual_param_idx_arr = NULL; if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } qual_info_arr = ftg_keygen_md->sdata_keygen_md.qual_info_arr; qual_info_count = ftg_keygen_md->sdata_keygen_md.qual_info_count; qual_param_idx_arr = ftg_keygen_md->sdata_keygen_md.qual_param_idx_arr; if ((qual_info_arr == NULL) || (qual_info_count <= 1)) { goto cleanup; } ft_info = ftg_keygen_md->ft_info; keygen_cfg.qual_cfg_info_db = ft_info->flow_data_qual_cfg; /* Create list of qualifier sizes */ for (idx = 0; idx < qual_info_count; idx++) { rv = bcmi_keygen_qual_cfg_max_size_get(unit, &keygen_cfg, qual_info_arr[idx].qual_id, &qual_size); BCMI_IF_ERROR_CLEANUP(rv); qual_size_arr[idx] = qual_size; } /* Sort qualifiers based on size and usage. Mask is not considered */ /* Set rank1_idx after ALU_DATA qualifier. */ rank1_idx = 1; for (idx = rank1_idx; idx < qual_info_count; idx++) { if ((qual_size_arr[idx] % 8) != 0) { /* If qual_size is not multiple of 8, Rank 1 */ rv = _field_hx5_ftg_keygen_qual_info_shift(unit, rank1_idx, idx, qual_info_arr, qual_size_arr, qual_param_idx_arr); BCMI_IF_ERROR_CLEANUP(rv); rank1_idx++; } } cleanup: ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_CFG_KEY_QUAL_ADJUST; } return rv; } /* * Function: * _field_hx5_ftg_keygen_cfg_key_qual_adjust * Purpose: * Re-arrange, if required, qual_info_arr for session key extraction. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_cfg_key_qual_adjust(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { /* Highest priority in the qual info arr */ #define _FP_FT_TRACKING_PARAM_USE_TYPE_HIGH (1 << 0) /* Use Keygen extractor A */ #define _FP_FT_TRACKING_PARAM_USE_TYPE_A (1 << 1) /* Use Keygen extractor A or B */ #define _FP_FT_TRACKING_PARAM_USE_TYPE_A_OR_B (1 << 2) int rv = BCM_E_NONE; int idx = 0; int rank1_idx = 0; int rank2_idx = 0; int mask_present = 0; int partial_mask = 0; uint16 qual_size = 0; uint16 qual_info_count = 0; uint16 qual_size_arr[20]; uint16 ext_type_arr[20]; uint16 *qual_param_idx_arr = NULL; bcmi_keygen_cfg_t keygen_cfg; _field_ft_info_t *ft_info = NULL; bcmi_keygen_qual_info_t *qual_info_arr = NULL; bcm_flowtracker_tracking_param_info_t *param_info = NULL; if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } qual_info_arr = ftg_keygen_md->skey_keygen_md.qual_info_arr; qual_info_count = ftg_keygen_md->skey_keygen_md.qual_info_count; qual_param_idx_arr = ftg_keygen_md->skey_keygen_md.qual_param_idx_arr; if ((qual_info_arr == NULL) || (qual_info_count <= 1)) { goto cleanup; } ft_info = ftg_keygen_md->ft_info; keygen_cfg.qual_cfg_info_db = ft_info->flow_key_qual_cfg; /* Create list of qualifier sizes */ for (idx = 0; idx < qual_info_count; idx++) { rv = bcmi_keygen_qual_cfg_max_size_get(unit, &keygen_cfg, qual_info_arr[idx].qual_id, &qual_size); BCM_IF_ERROR_RETURN(rv); qual_size_arr[idx] = qual_size; if (qual_size > 104) { ext_type_arr[idx] = _FP_FT_TRACKING_PARAM_USE_TYPE_HIGH; continue; } mask_present = 0; partial_mask = -1; param_info = &ftg_keygen_md->tracking_params_info[qual_param_idx_arr[idx]]; rv = bcmi_esw_ft_group_tracking_param_mask_status_get(unit, param_info, qual_size/8, &mask_present, &partial_mask); BCMI_IF_ERROR_CLEANUP(rv); if (mask_present == 0) { if ((qual_size == 8) || (qual_size == 24)) { ext_type_arr[idx] = _FP_FT_TRACKING_PARAM_USE_TYPE_A; } else { ext_type_arr[idx] = _FP_FT_TRACKING_PARAM_USE_TYPE_A_OR_B; } } else { if (partial_mask != -1) { ext_type_arr[idx] = _FP_FT_TRACKING_PARAM_USE_TYPE_A; } else { ext_type_arr[idx] = _FP_FT_TRACKING_PARAM_USE_TYPE_A_OR_B; } } } /* Based on Keygen extractor type, shuffle qual_info_arr */ /* Note that A_OR_B extractor types are pushed to the end */ rank1_idx = rank2_idx = 0; for (idx = 0; idx < qual_info_count; idx++) { if (ext_type_arr[idx] == _FP_FT_TRACKING_PARAM_USE_TYPE_HIGH) { rv = _field_hx5_ftg_keygen_qual_info_shift(unit, rank1_idx, idx, qual_info_arr, qual_size_arr, qual_param_idx_arr); BCMI_IF_ERROR_CLEANUP(rv); rank1_idx++; rank2_idx++; } else if (ext_type_arr[idx] == _FP_FT_TRACKING_PARAM_USE_TYPE_A) { rv = _field_hx5_ftg_keygen_qual_info_shift(unit, rank2_idx, idx, qual_info_arr, qual_size_arr, qual_param_idx_arr); BCMI_IF_ERROR_CLEANUP(rv); rank2_idx++; } } cleanup: ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_DATA_OPER_EXTRACT; } return rv; } /* * Function: * _field_hx5_ftg_keygen_data_oper_extract * Purpose: * Call keygen algo to extract session data. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_data_oper_extract(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int mode_idx = 0; int ext_modes_count = 0; _field_ft_info_t *ft_info = NULL; bcmi_keygen_mode_t ext_modes[2]; bcmi_keygen_cfg_t keygen_cfg; bcmi_keygen_oper_t *keygen_oper = NULL; bcmi_keygen_mode_t keygen_mode = BCMI_KEYGEN_MODE_SINGLE; bcmi_keygen_mode_t keygen_ext_mode = BCMI_KEYGEN_MODE_SINGLE; _field_ft_group_keydata_keygen_md_t *sdata_keygen_md = NULL; ft_info = ftg_keygen_md->ft_info; sdata_keygen_md = &ftg_keygen_md->sdata_keygen_md; /* Session data extraction modes */ if ((ftg_keygen_md->ft_type_bmp == BCMI_FT_TYPE_F_MICRO) || (ftg_keygen_md->ft_type_bmp == BCMI_FT_TYPE_F_AIFT)) { ext_modes_count = 1; ext_modes[0] = BCMI_KEYGEN_MODE_SINGLE; } for (mode_idx = 0; mode_idx < ext_modes_count; mode_idx++) { switch(ext_modes[mode_idx]) { case BCMI_KEYGEN_MODE_SINGLE: keygen_mode = BCMI_KEYGEN_MODE_SINGLE; keygen_ext_mode = BCMI_KEYGEN_MODE_SINGLE; sal_memset(&keygen_cfg, 0, sizeof(bcmi_keygen_cfg_t)); keygen_cfg.qual_info_arr = sdata_keygen_md->qual_info_arr; keygen_cfg.qual_info_count = sdata_keygen_md->qual_info_count; keygen_cfg.qual_cfg_info_db = ft_info->flow_data_qual_cfg; keygen_cfg.ext_cfg_db = ft_info->flow_key_ext_cfg_arr[keygen_ext_mode]; keygen_cfg.mode = keygen_mode; keygen_cfg.num_parts = 2; keygen_cfg.flags |= BCMI_KEYGEN_CFG_FLAGS_SERIAL_MUX_ALLOC; keygen_oper = &sdata_keygen_md->keygen_oper; sal_memset(keygen_oper, 0, sizeof(bcmi_keygen_oper_t)); rv = bcmi_keygen_cfg_process(unit, &keygen_cfg, keygen_oper); break; default: rv = BCM_E_INTERNAL; } if (BCM_SUCCESS(rv)) { break; } } /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { sdata_keygen_md->keygen_mode = keygen_mode; sdata_keygen_md->num_parts = keygen_cfg.num_parts; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_KEY_OPER_EXTRACT; } return rv; } /* * Function: * _field_ftg_keygen_key_qual_skip * Purpose: * Check if it is required to skip first qualifier. * In case there are two qualifiers which ar 128 bits, * rest of qualifiers cannot be masked as all Type A * are exhausted. This could be a problem with IPv6 * 5-tuple. To prevent it, if 2 such qualifiers are * present if is better to skip one qualifier and * extract it statically at the end of Key. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (IN) FT Group Keygen metadata. * skip_keygen_oper - (OUT) Keygen operational state for skipped * qualifier. * skipped - (OUT) If qualifier is skipped. * Returns: * BCM_E_XXX * Notes: * In function _field_hx5_ftg_keygen_cfg_key_qual_adjust(), we * sort qualifiers are place 128-bit extractors in the front. * It is pre-requisite to this function to work properly. */ STATIC int _field_ftg_keygen_key_qual_skip(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md, bcmi_keygen_oper_t *skip_keygen_oper, int *skipped) { int rv = BCM_E_NONE; int idx = 0, p_idx = 0; int qual_count = 0; int mask_present[2], partial_mask[2]; int type_a_ext_req = 0; int type_b_ext_req = 0; bcm_field_qualify_t qual; uint16 qual_size = 0; bcmi_keygen_qual_info_t temp_qual_info; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _field_ft_group_keydata_keygen_md_t *skey_keygen_md = NULL; bcm_flowtracker_tracking_param_info_t *param_info = NULL; map_db = ftg_keygen_md->ft_info->param_qual_map_db; skey_keygen_md = &ftg_keygen_md->skey_keygen_md; for (idx = 0; idx < 2; idx++) { if (skey_keygen_md->qual_info_count > idx) { qual = skey_keygen_md->qual_info_arr[idx].qual_id; if ((qual == bcmFieldQualifySrcIp6) || (qual == bcmFieldQualifyDstIp6) || (qual == bcmFieldQualifyInnerSrcIp6) || (qual == bcmFieldQualifyInnerDstIp6)) { qual_count++; /* Update qual_param_idx_arr when we did shuffle */ /* Get mask status */ p_idx = skey_keygen_md->qual_param_idx_arr[idx]; param_info = &ftg_keygen_md->tracking_params_info[p_idx]; pq_map = map_db->param_qual_map[param_info->param]; qual_size = pq_map->width/8; mask_present[idx] = 0; partial_mask[idx] = -1; rv = bcmi_esw_ft_group_tracking_param_mask_status_get(unit, param_info, qual_size, &mask_present[idx], &partial_mask[idx]); BCM_IF_ERROR_RETURN(rv); } } } if (qual_count < 2) { *skipped = FALSE; return BCM_E_NONE; } /* Skipping is required */ *skipped = TRUE; /* Skip qualifier which needs less type A */ if (partial_mask[1] < partial_mask[0]) { p_idx = skey_keygen_md->qual_param_idx_arr[0]; sal_memcpy(&temp_qual_info, &skey_keygen_md->qual_info_arr[0], sizeof(bcmi_keygen_qual_info_t)); skey_keygen_md->qual_param_idx_arr[0] = skey_keygen_md->qual_param_idx_arr[1]; sal_memcpy(&skey_keygen_md->qual_info_arr[0], &skey_keygen_md->qual_info_arr[1], sizeof(bcmi_keygen_qual_info_t)); skey_keygen_md->qual_param_idx_arr[1] = p_idx; sal_memcpy(&skey_keygen_md->qual_info_arr[1], &temp_qual_info, sizeof(bcmi_keygen_qual_info_t)); partial_mask[0] = partial_mask[1]; } if (partial_mask[0] != -1) { type_a_ext_req = partial_mask[0]/2; type_b_ext_req = qual_size/2 - partial_mask[0]/2; } /* If partial mask is not present or required extractors for type B exceeds extraction boundary */ if ((partial_mask[0] == -1) || (type_b_ext_req > 6)) { type_a_ext_req = 2; type_b_ext_req = 6; } /* Get required extractors */ rv = _field_ft_keygen_oper_skip_ext_ctrl_form(unit, skey_keygen_md->qual_info_arr[0].qual_id, type_a_ext_req, type_b_ext_req, skip_keygen_oper); BCM_IF_ERROR_RETURN(rv); /* Form qual_offset_info */ rv = _field_ft_keygen_oper_skip_qual_offset_info_form(unit, 3, skey_keygen_md->qual_info_arr[0].qual_id, type_a_ext_req, type_b_ext_req, skip_keygen_oper); BCM_IF_ERROR_RETURN(rv); return BCM_E_NONE; } /* * Function: * _field_ftg_keygen_oper_extract_verify * Purpose: * Verify extraction of qualifier in Keygen Type B. * Since type B does not support masking, any qualifier * with size not multiple of 16 will fail. * Parameters: * unit - (IN) BCM device number. * keygen_cfg - (IN) Keygen config. * keygen_oper - (IN) Keygen oper. * Returns: * BCM_E_XXX * Notes: */ STATIC int _field_ftg_keygen_oper_extract_verify(int unit, bcmi_keygen_cfg_t *keygen_cfg, bcmi_keygen_oper_t *keygen_oper) { int i = 0; int num_offsets = 0; int offset = 0; int q_width = 0; bcmi_keygen_qual_offset_info_t *qual_offset_info = NULL; if (keygen_cfg->num_parts == 3) { qual_offset_info = &keygen_oper->qual_offset_info[2]; } else { qual_offset_info = &keygen_oper->qual_offset_info[1]; } for (i = 0; i < qual_offset_info->size; i++) { num_offsets = 0; for (offset = 0; offset < BCMI_KEYGEN_QUAL_OFFSETS_MAX; offset++) { if (!qual_offset_info->offset_arr[i].width[offset]) { continue; } q_width = qual_offset_info->offset_arr[i].width[offset]; if (q_width != 16) { LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Failed to" " Allocate resources for Session" " Key tracking param\n\r"))); return BCM_E_RESOURCE; } num_offsets++; if (num_offsets == qual_offset_info->offset_arr[i].num_offsets) { break; } } } return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_key_oper_extract * Purpose: * Call keygen algo to extract session key. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_key_oper_extract(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int part = 0; int mode_idx = 0; int ext_modes_count = 0; int skipped = FALSE; _field_ft_info_t *ft_info = NULL; bcmi_keygen_cfg_t keygen_cfg; bcmi_keygen_oper_t skip_keygen_oper; bcmi_keygen_oper_t *keygen_oper = NULL; bcmi_keygen_mode_t ext_modes[2] = {0}; bcmi_keygen_mode_t keygen_mode = BCMI_KEYGEN_MODE_SINGLE; bcmi_keygen_mode_t keygen_ext_mode = BCMI_KEYGEN_MODE_SINGLE; _field_ft_group_keydata_keygen_md_t *skey_keygen_md = NULL; ft_info = ftg_keygen_md->ft_info; skey_keygen_md = &ftg_keygen_md->skey_keygen_md; sal_memset(&keygen_cfg, 0, sizeof(bcmi_keygen_cfg_t)); sal_memset(&skip_keygen_oper, 0, sizeof (skip_keygen_oper)); /* Skip if No Qualifier in Key */ if (skey_keygen_md->qual_info_count == 0) { goto cleanup; } rv = _field_ftg_keygen_key_qual_skip(unit, ftg_keygen_md, &skip_keygen_oper, &skipped); BCMI_IF_ERROR_CLEANUP(rv); if (skipped == TRUE) { ext_modes[0] = BCMI_KEYGEN_MODE_DBLINTRA; ext_modes_count = 1; } else { ext_modes[0] = BCMI_KEYGEN_MODE_SINGLE; ext_modes[1] = BCMI_KEYGEN_MODE_DBLINTRA; ext_modes_count = 2; } for (mode_idx = 0; mode_idx < ext_modes_count; mode_idx++) { switch(ext_modes[mode_idx]) { case BCMI_KEYGEN_MODE_SINGLE: keygen_mode = BCMI_KEYGEN_MODE_SINGLE; keygen_ext_mode = BCMI_KEYGEN_MODE_SINGLE; sal_memset(&keygen_cfg, 0, sizeof(bcmi_keygen_cfg_t)); keygen_cfg.qual_info_arr = skey_keygen_md->qual_info_arr; keygen_cfg.qual_info_count = skey_keygen_md->qual_info_count; keygen_cfg.qual_cfg_info_db = ft_info->flow_key_qual_cfg; keygen_cfg.ext_cfg_db = ft_info->flow_key_ext_cfg_arr[keygen_ext_mode]; keygen_cfg.mode = keygen_mode; keygen_cfg.num_parts = 2; keygen_cfg.flags |= BCMI_KEYGEN_CFG_FLAGS_SERIAL_MUX_ALLOC; keygen_oper = &skey_keygen_md->keygen_oper; sal_memset(keygen_oper, 0, sizeof(bcmi_keygen_oper_t)); rv = bcmi_keygen_cfg_process(unit, &keygen_cfg, keygen_oper); break; case BCMI_KEYGEN_MODE_DBLINTRA: keygen_mode = BCMI_KEYGEN_MODE_DBLINTRA; keygen_ext_mode = BCMI_KEYGEN_MODE_DBLINTRA; sal_memset(&keygen_cfg, 0, sizeof(bcmi_keygen_cfg_t)); if (skipped == TRUE) { /* Remove static qual/extractor from qual_info_arr */ keygen_cfg.flags |= BCMI_KEYGEN_CFG_FLAGS_QSET_UPDATE; keygen_cfg.qual_info_arr = &skey_keygen_md->qual_info_arr[1]; keygen_cfg.qual_info_count = skey_keygen_md->qual_info_count - 1; keygen_cfg.ext_ctrl_sel_info = skip_keygen_oper.ext_ctrl_sel_info; keygen_cfg.ext_ctrl_sel_info_count = skip_keygen_oper.ext_ctrl_sel_info_count; } else { keygen_cfg.qual_info_arr = &skey_keygen_md->qual_info_arr[0]; keygen_cfg.qual_info_count = skey_keygen_md->qual_info_count; } keygen_cfg.qual_cfg_info_db = ft_info->flow_key_qual_cfg; keygen_cfg.ext_cfg_db = ft_info->flow_key_ext_cfg_arr[keygen_ext_mode]; keygen_cfg.mode = keygen_mode; keygen_cfg.num_parts = 3; keygen_cfg.flags |= BCMI_KEYGEN_CFG_FLAGS_SERIAL_MUX_ALLOC; keygen_oper = &skey_keygen_md->keygen_oper; sal_memset(keygen_oper, 0, sizeof(bcmi_keygen_oper_t)); rv = bcmi_keygen_cfg_process(unit, &keygen_cfg, keygen_oper); break; default: rv = BCM_E_INTERNAL; BCMI_IF_ERROR_CLEANUP(rv); } if (BCM_SUCCESS(rv) && (skipped == TRUE)) { /* Merge skipped keygen cfg to get final keygen oper */ rv = _field_ft_keygen_skip_qual_ext_ctrl_merge(unit, keygen_cfg.num_parts, &skip_keygen_oper, keygen_oper); } if (BCM_SUCCESS(rv)) { /* Verify extraction */ rv = _field_ftg_keygen_oper_extract_verify(unit, &keygen_cfg, keygen_oper); if (BCM_SUCCESS(rv)) { /* Break if extraction is successful */ break; } } } cleanup: /* Free up skip_keygen_oper */ if (skip_keygen_oper.qual_offset_info != NULL) { for (part = 0; part < 3; part++) { if (skip_keygen_oper.qual_offset_info[part].qid_arr != NULL) { sal_free(skip_keygen_oper.qual_offset_info[part].qid_arr); skip_keygen_oper.qual_offset_info[part].qid_arr = NULL; } if (skip_keygen_oper.qual_offset_info[part].offset_arr != NULL) { sal_free(skip_keygen_oper.qual_offset_info[part].offset_arr); skip_keygen_oper.qual_offset_info[part].offset_arr = NULL; } } sal_free(skip_keygen_oper.qual_offset_info); } if (skip_keygen_oper.ext_ctrl_sel_info != NULL) { sal_free(skip_keygen_oper.ext_ctrl_sel_info); skip_keygen_oper.ext_ctrl_sel_info = NULL; } /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { skey_keygen_md->keygen_mode = keygen_mode; skey_keygen_md->num_parts = keygen_cfg.num_parts; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_DATA_OPER_PROCESS; } return rv; } /* * Function: * _field_hx5_ftg_flowcheck_oper_process * Purpose: * Process Session data keygen_oper for flowcheck info. * Parameters: * unit - (IN) BCM device number. * qual_ext_offset_info - (IN) Qual-Extractor info * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Tracking Params which belongs to MFT/EFT stage are not * processed here. Handled separately in new stage process * added. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_flowcheck_oper_process(int unit, _field_ft_qual_ext_offset_info_t *qual_ext_offset_info, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int sd_idx = 0; int data_idx = 0; int q_idx = 0; int width = 0; int start = 0; int temp_fc_idx = 0; int fc_idx = 0; int num_operands = 0; uint16 ext_ft_type_flag = 0; uint16 chk_ft_type_bmp = 0; bcmi_ft_alu_key_t *sdata_info_key = NULL; bcm_field_qualify_t qual; bcm_flowtracker_check_t check_id; bcmi_ft_group_alu_info_t *sdata_info = NULL; bcm_flowtracker_check_info_t fc_info; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; bcm_flowtracker_check_action_info_t action_info; bcmi_ft_type_t ext_ft_type = bcmiFtTypeNone; map_db = ftg_keygen_md->ft_info->param_qual_map_db; sdata_info = ftg_keygen_md->keydata_oper_info.sdata_info; data_idx = ftg_keygen_md->keydata_oper_info.num_sdata_info; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_IFT) { ext_ft_type = bcmiFtTypeIFT; ext_ft_type_flag = BCMI_FT_TYPE_F_IFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AIFT) { ext_ft_type = bcmiFtTypeAIFT; ext_ft_type_flag = BCMI_FT_TYPE_F_AIFT; } for (idx = 0; idx < ftg_keygen_md->num_flowchecks; idx++) { check_id = ftg_keygen_md->flowtracker_checks[idx]; bcm_flowtracker_check_info_t_init(&fc_info); rv = bcmi_ft_check_get(unit, check_id, &fc_info, &chk_ft_type_bmp); BCM_IF_ERROR_RETURN(rv); /* Skip non IFT checkers and add checkers with none as IFT */ if (!(chk_ft_type_bmp & ext_ft_type_flag)) { continue; } fc_idx = BCMI_FT_FLOWCHECKER_INDEX_GET(check_id); /* Search if flowcheck is already added in sdata_info */ for (sd_idx = 0; sd_idx < data_idx; sd_idx++) { temp_fc_idx = BCMI_FT_FLOWCHECKER_INDEX_GET(sdata_info[sd_idx].flowchecker_id); if (temp_fc_idx == fc_idx) { break; } } /* If not found, use last and increment data_idx */ if (sd_idx == data_idx) { data_idx++; } sdata_info[sd_idx].flowchecker_id = BCMI_FT_FLOWCHECKER_INDEX_SET(fc_idx, BCM_FT_IDX_TYPE_CHECK); if (BCMI_FT_IDX_IS_2ND_CHECK(check_id)) { sdata_info[sd_idx].element_type2 = fc_info.param; sdata_info_key = &sdata_info[sd_idx].key2; sdata_info[sd_idx].alu_ft_type = ext_ft_type; sdata_info[sd_idx].custom_id2 = fc_info.custom_id; } else { sdata_info[sd_idx].element_type1 = fc_info.param; sdata_info_key = &sdata_info[sd_idx].key1; sdata_info[sd_idx].alu_ft_type = ext_ft_type; sdata_info[sd_idx].custom_id1 = fc_info.custom_id; } pq_map = map_db->param_qual_map[fc_info.param]; if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_FILL) { continue; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED) { sdata_info_key->location = 0; sdata_info_key->length = pq_map->width; sdata_info_key->is_alu = 1; } else { if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = _field_ft_group_param_udf_qual_get(unit, &ftg_keygen_md->sdata_keygen_md, fc_info.param, fc_info.custom_id, &qual); BCM_IF_ERROR_RETURN(rv); } else { qual = pq_map->qual; } for (q_idx = 0; q_idx < qual_ext_offset_info->size; q_idx++) { if (qual_ext_offset_info->qid_arr[q_idx] != qual) { continue; } start = width = 0; rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[q_idx], &start, &width); BCM_IF_ERROR_RETURN(rv); sdata_info_key->location = start; sdata_info_key->length = width; sdata_info_key->is_alu = 1; break; } if (q_idx == qual_ext_offset_info->size) { BCM_IF_ERROR_RETURN(BCM_E_INTERNAL); } } /* Set action key from primary flowcheck */ if (!BCMI_FT_IDX_IS_2ND_CHECK(check_id)) { bcm_flowtracker_check_action_info_t_init(&action_info); rv = bcm_esw_flowtracker_check_action_info_get(unit, check_id, &action_info); BCM_IF_ERROR_RETURN(rv); /* Check if Action is valid */ if (action_info.action == bcmFlowtrackerCheckActionNone) { continue; } /* Set direction */ sdata_info[sd_idx].direction = action_info.direction; /* If Action does not requires param, continue */ rv = bcmi_esw_ft_check_action_num_operands_get(unit, action_info.action, &num_operands); BCM_IF_ERROR_RETURN(rv); if (num_operands == 0) { continue; } pq_map = map_db->param_qual_map[action_info.param]; /* Skip if non IFT/AIFT stage */ if (!(pq_map->db_ft_type_bmp & ext_ft_type_flag)) { continue; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED) { sdata_info[sd_idx].action_element_type = action_info.param; sdata_info[sd_idx].action_key.location = pq_map->start; sdata_info[sd_idx].action_key.length = pq_map->width; sdata_info[sd_idx].action_key.is_alu = 1; } else { if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = _field_ft_group_param_udf_qual_get(unit, &ftg_keygen_md->sdata_keygen_md, action_info.param, action_info.custom_id, &qual); BCM_IF_ERROR_RETURN(rv); } else { qual = pq_map->qual; } for (q_idx = 0; q_idx < qual_ext_offset_info->size; q_idx++) { if (qual_ext_offset_info->qid_arr[q_idx] != qual) { continue; } start = width = 0; rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[q_idx], &start, &width); BCM_IF_ERROR_RETURN(rv); sdata_info[sd_idx].action_element_type = action_info.param; sdata_info[sd_idx].action_key.location = start; sdata_info[sd_idx].action_key.length = width; sdata_info[sd_idx].action_key.is_alu = 1; sdata_info[sd_idx].action_custom_id = action_info.custom_id; break; } if (q_idx == qual_ext_offset_info->size) { BCM_IF_ERROR_RETURN(BCM_E_INTERNAL); } } } } ftg_keygen_md->keydata_oper_info.num_sdata_info = data_idx; return rv; } /* * Function: * _field_hx5_ftg_tracking_params_oper_process * Purpose: * Process Session data keygen_oper for tracking params.. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Tracking Params which belongs to MFT/EFT stage are not * processed here. Handled separately in new stage process * added. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_tracking_params_oper_process(int unit, _field_ft_qual_ext_offset_info_t *qual_ext_offset_info, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int width = 0; int idx = 0; int data_idx = 0; int q_idx = 0; int start_bit = 0; uint16 param = 0; uint16 ext_ft_type_flag = 0; bcm_field_qualify_t qual; bcmi_ft_type_t ext_ft_type = bcmiFtTypeNone; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _field_ft_group_keygen_oper_info_t *oper_info = NULL; bcm_flowtracker_tracking_param_info_t *tracking_param_info = NULL; oper_info = &ftg_keygen_md->keydata_oper_info; map_db = ftg_keygen_md->ft_info->param_qual_map_db; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_IFT) { ext_ft_type = bcmiFtTypeIFT; ext_ft_type_flag = BCMI_FT_TYPE_F_IFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AIFT) { ext_ft_type = bcmiFtTypeAIFT; ext_ft_type_flag = BCMI_FT_TYPE_F_AIFT; } data_idx = oper_info->num_sdata_info; idx = 0; while(idx < ftg_keygen_md->num_tracking_params) { tracking_param_info = &ftg_keygen_md->tracking_params_info[idx]; if (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY) { idx++; continue; } param = tracking_param_info->param; pq_map = map_db->param_qual_map[param]; if ((!(pq_map->db_ft_type_bmp & ext_ft_type_flag)) || (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_FILL)) { idx++; continue; } if (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_STICKYOR_UPDATE) { oper_info->sdata_info[data_idx].flags |= BCMI_FT_ALU_LOAD_STICKYOR_UPDATE; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED) { oper_info->sdata_info[data_idx].key1.location = 0; oper_info->sdata_info[data_idx].key1.is_alu = ((pq_map->flags & _FP_FT_TRACKING_PARAM_F_ALU_REQ) ? 1 : 0); oper_info->sdata_info[data_idx].key1.length = pq_map->width; oper_info->sdata_info[data_idx].element_type1 = param; oper_info->sdata_info[data_idx].flowchecker_id = 0; oper_info->sdata_info[data_idx].alu_ft_type = ext_ft_type; oper_info->sdata_info[data_idx].direction = tracking_param_info->direction; data_idx++; } else { if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = _field_ft_group_param_udf_qual_get(unit, &ftg_keygen_md->sdata_keygen_md, param, tracking_param_info->custom_id, &qual); BCM_IF_ERROR_RETURN(rv); } else { qual = pq_map->qual; } for (q_idx = 0; q_idx < qual_ext_offset_info->size; q_idx++) { if (qual_ext_offset_info->qid_arr[q_idx] != qual) { continue; } start_bit = width = 0; rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[q_idx], &start_bit, &width); BCMI_IF_ERROR_CLEANUP(rv); oper_info->sdata_info[data_idx].key1.location = start_bit; oper_info->sdata_info[data_idx].key1.is_alu = 0; oper_info->sdata_info[data_idx].key1.length = width; oper_info->sdata_info[data_idx].element_type1 = param; oper_info->sdata_info[data_idx].flowchecker_id = 0; oper_info->sdata_info[data_idx].alu_ft_type = ext_ft_type; oper_info->sdata_info[data_idx].direction = tracking_param_info->direction; oper_info->sdata_info[data_idx].custom_id1 = tracking_param_info->custom_id; data_idx++; break; } if (q_idx == qual_ext_offset_info->size) { BCM_IF_ERROR_RETURN(BCM_E_INTERNAL); } } idx++; } oper_info->num_sdata_info = data_idx; cleanup: return rv; } #ifdef BCM_FLOWTRACKER_V2_SUPPORT /* * Function: * _field_hx5_ftg_flowcheck_stage_oper_process * Purpose: * Process Session data keygen_oper for flowcheck info. * Parameters: * unit - (IN) BCM device number. * ft_type_in - (IN) Input Flow Tracker Type. * ftg_keygen_md - (IN/OUT) FT Group Keygen metadata. * Notes: * 1. This api is added to process flow checkers for * stage passed as input mostly mft/eft stages. * ift stage is processed separately. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_flowcheck_stage_oper_process(int unit, bcmi_ft_type_t ft_type_in, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int num_operands = 0; bcm_flowtracker_check_t check_id; int idx = 0, sd_idx = 0, data_idx = 0, fc_idx = 0, temp_fc_idx = 0; bcmi_ft_alu_key_t *sdata_info_key = NULL; bcmi_ft_group_alu_info_t *sdata_info = NULL; bcmi_flowtracker_flowchecker_info_t fc_info; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; map_db = ftg_keygen_md->ft_info->param_qual_map_db; /* Allocate if sdata_info is NULL */ if ((ftg_keygen_md->keydata_oper_info.sdata_info == NULL) && (ftg_keygen_md->sdata_keygen_md.max_qual_info_alloc)) { _FP_XGS3_ALLOC(ftg_keygen_md->keydata_oper_info.sdata_info, ftg_keygen_md->sdata_keygen_md.max_qual_info_alloc * \ sizeof(bcmi_ft_group_alu_info_t), "session data info"); if (ftg_keygen_md->keydata_oper_info.sdata_info == NULL) { return BCM_E_MEMORY; } } sdata_info = ftg_keygen_md->keydata_oper_info.sdata_info; if (sdata_info == NULL) { return BCM_E_PARAM; } data_idx = ftg_keygen_md->keydata_oper_info.num_sdata_info; /* add all flowcheckers */ for (idx = 0; idx < ftg_keygen_md->num_flowchecks; idx++) { check_id = ftg_keygen_md->flowtracker_checks[idx]; sal_memset(&fc_info, 0, sizeof(bcmi_flowtracker_flowchecker_info_t)); rv = bcmi_ft_flowchecker_get(unit, check_id, &fc_info); BCM_IF_ERROR_RETURN(rv); if (BCMI_FT_IDX_IS_2ND_CHECK(check_id)) { pq_map = map_db->param_qual_map[fc_info.check2.param]; } else { pq_map = map_db->param_qual_map[fc_info.check1.param]; } /* Skip if ft type do not match, extract pending */ if (!(fc_info.check_ft_type_bmp & (1 << ft_type_in))) { continue; } /* Skip if no need to add, nothing to extract */ if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_FILL) { continue; } /* Search if flowcheck is already added in sdata_info */ fc_idx = BCMI_FT_FLOWCHECKER_INDEX_GET(check_id); for (sd_idx = 0; sd_idx < data_idx; sd_idx++) { if (sdata_info[sd_idx].flowchecker_id) { temp_fc_idx = BCMI_FT_FLOWCHECKER_INDEX_GET (sdata_info[sd_idx].flowchecker_id); if (temp_fc_idx == fc_idx) { break; } } } /* If not found, use last and increment data_idx */ if (sd_idx == data_idx) { data_idx++; } sdata_info[sd_idx].flowchecker_id = BCMI_FT_FLOWCHECKER_INDEX_SET(fc_idx, BCM_FT_IDX_TYPE_CHECK); if (BCMI_FT_IDX_IS_2ND_CHECK(check_id)) { sdata_info[sd_idx].element_type2 = fc_info.check2.param; sdata_info_key = &sdata_info[sd_idx].key2; } else { sdata_info[sd_idx].element_type1 = fc_info.check1.param; sdata_info_key = &sdata_info[sd_idx].key1; } sdata_info_key->location = pq_map->start; sdata_info_key->length = pq_map->width; sdata_info_key->is_alu = 1; sdata_info[sd_idx].alu_ft_type = ft_type_in; /* Set action key from primary flowcheck */ if (!BCMI_FT_IDX_IS_2ND_CHECK(check_id)) { /* Check if Action is valid */ if (fc_info.action_info.action == bcmFlowtrackerCheckActionNone) { continue; } /* Set direction */ sdata_info[sd_idx].direction = fc_info.action_info.direction; /* If Action does not requires param, continue */ rv = bcmi_esw_ft_check_action_num_operands_get(unit, fc_info.action_info.action, &num_operands); BCM_IF_ERROR_RETURN(rv); if (num_operands == 0) { continue; } pq_map = map_db->param_qual_map[fc_info.action_info.param]; sdata_info[sd_idx].action_element_type = fc_info.action_info.param; sdata_info[sd_idx].action_key.location = pq_map->start; sdata_info[sd_idx].action_key.length = pq_map->width; sdata_info[sd_idx].action_key.is_alu = 1; } } ftg_keygen_md->keydata_oper_info.num_sdata_info = data_idx; return rv; } /* * Function: * _field_hx5_ftg_tracking_params_stage_oper_process * Purpose: * Process Session data keygen_oper for tracking params.. * Parameters: * unit - (IN) BCM device number. * ft_type_in - (IN) Input Flow Tracker Type. * ftg_keygen_md - (IN/OUT) FT Group Keygen metadata. * Notes: * 1. This api is added to process flow checkers for * stage passed as input mostly mft/eft stages. * ift stage is processed separately. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_tracking_params_stage_oper_process(int unit, bcmi_ft_type_t ft_type_in, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int data_idx = 0; uint16 param = 0; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_group_keygen_oper_info_t *oper_info = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; bcm_flowtracker_tracking_param_info_t *tracking_param_info = NULL; oper_info = &ftg_keygen_md->keydata_oper_info; map_db = ftg_keygen_md->ft_info->param_qual_map_db; data_idx = oper_info->num_sdata_info; idx = 0; while(idx < ftg_keygen_md->num_tracking_params) { tracking_param_info = &ftg_keygen_md->tracking_params_info[idx]; param = tracking_param_info->param; pq_map = map_db->param_qual_map[param]; /* Skip if param is Key of belongs to different ft type */ if ((!(pq_map->db_ft_type_bmp & (1 << ft_type_in))) || (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY)) { idx++; continue; } /* Skip if no need to add */ if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_FILL) { idx++; continue; } if (tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_STICKYOR_UPDATE) { oper_info->sdata_info[data_idx].flags |= BCMI_FT_ALU_LOAD_STICKYOR_UPDATE; } oper_info->sdata_info[data_idx].key1.location = pq_map->start; oper_info->sdata_info[data_idx].key1.is_alu = ((pq_map->flags & _FP_FT_TRACKING_PARAM_F_ALU_REQ) ? 1 : 0); oper_info->sdata_info[data_idx].key1.length = pq_map->width; oper_info->sdata_info[data_idx].element_type1 = param; oper_info->sdata_info[data_idx].flowchecker_id = 0; oper_info->sdata_info[data_idx].alu_ft_type = ft_type_in; oper_info->sdata_info[data_idx].direction = tracking_param_info->direction; data_idx++; idx++; } oper_info->num_sdata_info = data_idx; return rv; } #endif /* * Function: * _field_hx5_ftg_alu_data_oper_process * Purpose: * Output of session data keygen is processed for ALU data * and results are saved in extractors codes. * Parameters: * unit - (IN) BCM device number. * qual_ext_offset_info - (IN) Qual-Extractor info. * ext_codes - (OUT) extractor codes. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_alu_data_oper_process(int unit, _field_ft_qual_ext_offset_info_t *qual_ext_offset_info, _field_ft_keygen_ext_codes_t *ext_codes, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int bit = 0; int q_idx = 0; int index = 0; int width = 0; int location = 0; int extract_pos = 0; int start = 0; int qual_width = 0; uint32 type_mask[1] = {0}; bcm_field_qualify_t qual; _field_ft_tracking_alu_data_info_t *alu_data_info = NULL; _field_ft_keygen_type_c_ext_t *type_c_extractors = NULL; if ((qual_ext_offset_info == NULL) || (ext_codes == NULL) || (ftg_keygen_md == NULL)) { return BCM_E_PARAM; } /* Return if ALU_DATA is not required */ if (!(ftg_keygen_md->flags & _FIELD_FTG_KEYGEN_F_ALU_DATA_REQ)) { return BCM_E_NONE; } type_c_extractors = &ext_codes->type_c_extractors; for (index = 0; index < ftg_keygen_md->num_alu_data; index++) { alu_data_info = &ftg_keygen_md->alu_data_info[index]; qual = alu_data_info->qual; extract_pos = alu_data_info->extract_pos; width = alu_data_info->width; for (q_idx = 0; q_idx < qual_ext_offset_info->size; q_idx++) { if (qual_ext_offset_info->qid_arr[q_idx] != qual) { continue; } start = qual_width = 0; rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[q_idx], &start, &qual_width); BCM_IF_ERROR_RETURN(rv); if ((start + width) > qual_width) { return BCM_E_INTERNAL; } location = start + alu_data_info->offset; for (bit = 0; bit < width; bit++) { type_c_extractors->l1_e1_sel[extract_pos + bit] = location + bit; } SHR_BITSET_RANGE(&type_mask[0], extract_pos, width); } } ext_codes->type_c_mask.mask = type_mask[0]; return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_data_oper_process * Purpose: * Process Session data keygen_oper. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_data_oper_process(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int num_sdata_info = 0; _field_ft_keygen_ext_codes_t ext_codes; _field_ft_qual_ext_offset_info_t *qual_ext_offset_info = NULL; _field_ft_group_keydata_keygen_md_t *sdata_keygen_md = NULL; _field_ft_group_keygen_oper_info_t *oper_info = NULL; oper_info = &ftg_keygen_md->keydata_oper_info; sdata_keygen_md = &ftg_keygen_md->sdata_keygen_md; /* Skip if nothing is extracted */ if (sdata_keygen_md->keygen_oper.ext_ctrl_sel_info_count == 0) { goto cleanup; } /* Get qualifier/extractors hw info from keygen_oper */ rv = _field_hx5_ftg_qual_ext_hw_info_get(unit, 0, ftg_keygen_md, &qual_ext_offset_info, &ext_codes); if (BCM_FAILURE(rv) || (qual_ext_offset_info == NULL)) { goto cleanup; } /* Allocate memory for flowtracker group session data db */ num_sdata_info = sdata_keygen_md->max_qual_info_alloc; _FP_XGS3_ALLOC(oper_info->sdata_info, num_sdata_info * sizeof(bcmi_ft_group_alu_info_t), "session data info"); if (oper_info->sdata_info == NULL) { BCMI_IF_ERROR_CLEANUP(BCM_E_MEMORY); } /* Prepare Session data from flowchecks */ if (BCM_SUCCESS(rv)) { rv = _field_hx5_ftg_flowcheck_oper_process(unit, qual_ext_offset_info, ftg_keygen_md); } /* Prepare Session data from tracking params */ if (BCM_SUCCESS(rv)) { rv = _field_hx5_ftg_tracking_params_oper_process(unit, qual_ext_offset_info, ftg_keygen_md); } /* Process alu data oper info */ if (BCM_SUCCESS(rv)) { rv = _field_hx5_ftg_alu_data_oper_process(unit, qual_ext_offset_info, &ext_codes, ftg_keygen_md); } /* Encode Session Data extractors. */ if (BCM_SUCCESS(rv)) { rv = _bcm_field_hx5_ft_extractors_encode(unit, &ext_codes, &oper_info->sdata_ext_count, &oper_info->sdata_ext_info); } cleanup: if (qual_ext_offset_info != NULL) { (void) _field_hx5_ft_qual_ext_offset_info_free(unit, &qual_ext_offset_info); } /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_KEY_OPER_PROCESS; } return rv; } STATIC int _field_ftg_tracking_param_mask_apply(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md, int qual_idx, _field_ft_qual_ext_offset_info_t *qual_ext_offset_info, bcm_flowtracker_tracking_param_info_t *tracking_param_info, _field_ft_keygen_ext_codes_t *ext_codes) { int rv = BCM_E_NONE; int q_offset = 0; int q_width = 0; int ext_num = 0; int num_offsets = 0; int offset = 0; int prev_width = 0; int mask_present = 0; uint8 *ptr = NULL; uint32 qual_bitmap[4]; _field_ft_info_t *ft_info = NULL; bcmi_keygen_cfg_t keygen_cfg; uint16 qual_size = 0; ft_info = ftg_keygen_md->ft_info; keygen_cfg.qual_cfg_info_db = ft_info->flow_key_qual_cfg; rv = bcmi_keygen_qual_cfg_max_size_get(unit, &keygen_cfg, qual_ext_offset_info->qid_arr[qual_idx], &qual_size); BCM_IF_ERROR_RETURN(rv); rv = bcmi_esw_ft_group_tracking_param_mask_status_get(unit, tracking_param_info, qual_size/8, &mask_present, NULL); BCM_IF_ERROR_RETURN(rv); if (mask_present == 0) { return BCM_E_NONE; } num_offsets = 0; prev_width = 0; for (offset = 0; offset < BCMI_KEYGEN_QUAL_OFFSETS_MAX; offset++) { if (!qual_ext_offset_info->offset_arr[qual_idx].width[offset]) { continue; } q_offset = qual_ext_offset_info->offset_arr[qual_idx].offset[offset]; q_width = qual_ext_offset_info->offset_arr[qual_idx].width[offset]; ext_num = qual_ext_offset_info->sel_offset_arr[qual_idx].ext_num[offset]; prev_width += q_width; ptr = tracking_param_info->mask + (qual_size/8) - (prev_width/8); if (q_width == 16) { _SHR_UNPACK_U16(ptr, qual_bitmap[0]); } else { _SHR_UNPACK_U8(ptr, qual_bitmap[0]); } rv = _bcm_field_ft_keygen_profile_extractors_mask_set(unit, q_offset, q_width, ext_num, NULL, 0, qual_bitmap, ext_codes); BCM_IF_ERROR_RETURN(rv); num_offsets++; if (num_offsets == qual_ext_offset_info->offset_arr[qual_idx].num_offsets) { break; } } return rv; } /* * Function: * _field_hx5_ftg_keygen_key_oper_process * Purpose: * Process Session data keygen_oper. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Notes: * 1. Added code to skip non IFT stage key processing. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_key_oper_process(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; int idx = 0; int key_idx = 0; int qual_idx = 0; int start_bit = 0; int width = 0; int num_skey_info = 0; uint16 param = 0; uint16 ext_ft_type_flag = 0; bcm_field_qualify_t qual; _field_ft_keygen_ext_codes_t ext_codes; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; _field_ft_group_keygen_oper_info_t *oper_info = NULL; _field_ft_group_keydata_keygen_md_t *skey_keygen_md = NULL; _field_ft_qual_ext_offset_info_t *qual_ext_offset_info = NULL; bcm_flowtracker_tracking_param_info_t *tracking_param_info = NULL; /* Skip if Key extraction is not required */ if (!(ftg_keygen_md->flags & _FIELD_FTG_KEYGEN_F_KEY_REQ)) { goto cleanup; } /* Get qualifier/extractors hw info from keygen_oper */ rv = _field_hx5_ftg_qual_ext_hw_info_get(unit, 1, ftg_keygen_md, &qual_ext_offset_info, &ext_codes); if (BCM_FAILURE(rv) || (qual_ext_offset_info == NULL)) { goto cleanup; } if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_IFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_IFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AIFT) { ext_ft_type_flag = BCMI_FT_TYPE_F_AIFT; } oper_info = &ftg_keygen_md->keydata_oper_info; map_db = ftg_keygen_md->ft_info->param_qual_map_db; skey_keygen_md = &ftg_keygen_md->skey_keygen_md; /* Allocate memory for flowtracker group session key db */ num_skey_info = skey_keygen_md->max_qual_info_alloc; _FP_XGS3_ALLOC(oper_info->skey_info, num_skey_info * sizeof(bcmi_ft_group_alu_info_t), "session key info"); if (oper_info->skey_info == NULL) { BCMI_IF_ERROR_CLEANUP(BCM_E_MEMORY); } key_idx = 0; while(idx < ftg_keygen_md->num_tracking_params) { tracking_param_info = &ftg_keygen_md->tracking_params_info[idx]; /* Skip if tracking param is not Key. */ if (!(tracking_param_info->flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY)) { idx++; continue; } param = tracking_param_info->param; pq_map = map_db->param_qual_map[param]; /* Skip if param is valid for extraction ft type */ if (!(pq_map->db_ft_type_bmp & ext_ft_type_flag)) { continue; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = _field_ft_group_param_udf_qual_get(unit, &ftg_keygen_md->skey_keygen_md, param, tracking_param_info->custom_id, &qual); BCMI_IF_ERROR_CLEANUP(rv); } else { qual = pq_map->qual; } for (qual_idx = 0; qual_idx < qual_ext_offset_info->size; qual_idx++) { if (qual_ext_offset_info->qid_arr[qual_idx] != qual) { continue; } start_bit = width = 0; rv = _field_hx5_ftg_qual_offset_width_get(unit, &qual_ext_offset_info->offset_arr[qual_idx], &start_bit, &width); BCMI_IF_ERROR_CLEANUP(rv); /* Apply tracking param mask */ rv = _field_ftg_tracking_param_mask_apply(unit, ftg_keygen_md, qual_idx, qual_ext_offset_info, tracking_param_info, &ext_codes); BCMI_IF_ERROR_CLEANUP(rv); oper_info->skey_info[key_idx].key1.location = start_bit; oper_info->skey_info[key_idx].key1.is_alu = 0; oper_info->skey_info[key_idx].key1.length = width; oper_info->skey_info[key_idx].element_type1 = param; oper_info->skey_info[key_idx].flowchecker_id = 0; oper_info->skey_info[key_idx].custom_id1 = tracking_param_info->custom_id; key_idx++; break; } if (qual_idx == qual_ext_offset_info->size) { BCM_IF_ERROR_RETURN(BCM_E_INTERNAL); } idx++; } oper_info->num_skey_info = key_idx; if (skey_keygen_md->keygen_mode == BCMI_KEYGEN_MODE_SINGLE) { oper_info->mode = bcmiFtGroupModeSingle; } else { oper_info->mode = bcmiFtGroupModeDouble; } /* Dump Hardware Extraction codes */ LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "After" " applying session key param mask...\n\r"))); (void) _bcm_field_hx5_ft_keygen_hw_extractors_dump(unit, &ext_codes); /* Encode Session Key extractors. */ rv = _bcm_field_hx5_ft_extractors_encode(unit, &ext_codes, &oper_info->skey_ext_count, &oper_info->skey_ext_info); cleanup: if (qual_ext_offset_info != NULL) { (void) _field_hx5_ft_qual_ext_offset_info_free(unit, &qual_ext_offset_info); } /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_MFT_DATA_PROCESS; } return rv; } /* * Function: * _field_hx5_ftg_keygen_mft_stage_process * * Purpose: * Process mft stage tracking param & flow checkers. * * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * * Notes: * This step is added to process flow checkers & * tracking params belonging to MFT stage alone. * * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_mft_stage_process(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; /* Input Param Check */ if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } #ifdef BCM_FLOWTRACKER_V2_SUPPORT if (soc_feature(unit, soc_feature_flex_flowtracker_ver_2)) { bcmi_ft_type_t ext_ft_type = bcmiFtTypeNone; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_MFT) { ext_ft_type = bcmiFtTypeMFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AMFT) { ext_ft_type = bcmiFtTypeAMFT; } if (ext_ft_type != bcmiFtTypeNone) { /* Process Flow Checkers for MFT Stage */ rv = _field_hx5_ftg_flowcheck_stage_oper_process(unit, ext_ft_type, ftg_keygen_md); BCMI_IF_ERROR_CLEANUP(rv); /* Process Tracking Params for MFT Stage */ rv = _field_hx5_ftg_tracking_params_stage_oper_process(unit, ext_ft_type, ftg_keygen_md); } } cleanup: /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_EFT_DATA_PROCESS; } #else ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_EFT_DATA_PROCESS; #endif return rv; } /* * Function: * _field_hx5_ftg_keygen_eft_stage_process * * Purpose: * Process eft stage tracking param & flow checkers. * * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * * Notes: * This step is added to process flow checkers & * tracking params belonging to EFT stage alone. * * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_eft_stage_process(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; /* Input Param Check */ if (ftg_keygen_md == NULL) { return (BCM_E_PARAM); } #ifdef BCM_FLOWTRACKER_V2_SUPPORT if (soc_feature(unit, soc_feature_flex_flowtracker_ver_2)) { bcmi_ft_type_t ext_ft_type = bcmiFtTypeNone; if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_EFT) { ext_ft_type = bcmiFtTypeEFT; } else if (ftg_keygen_md->ft_type_bmp & BCMI_FT_TYPE_F_AEFT) { ext_ft_type = bcmiFtTypeAEFT; } if (ext_ft_type != bcmiFtTypeNone) { /* Process Flow Checkers for EFT Stage */ rv = _field_hx5_ftg_flowcheck_stage_oper_process(unit, ext_ft_type, ftg_keygen_md); BCMI_IF_ERROR_CLEANUP(rv); /* Process Tracking Params for EFT Stage */ rv = _field_hx5_ftg_tracking_params_stage_oper_process(unit, ext_ft_type, ftg_keygen_md); } } cleanup: /* Move to next state */ ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; if (BCM_FAILURE(rv)) { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; } else { ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_OPER_SAVE; } #else ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_OPER_SAVE; #endif return rv; } /* * Function: * _field_hx5_ftg_keygen_oper_save * Purpose: * Save FT Group Session Key/Data to FT Group DB. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_PARAM - Invalid inputs. * BCM_E_MEMORY - Failed to allocate memory. * BCM_E_NONE - Success. */ STATIC int _field_hx5_ftg_keygen_oper_save(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; bcm_flowtracker_group_t ft_group_id; _field_ft_group_keygen_oper_info_t *oper_info = NULL; /* Dump Session Key and Session Data */ _field_hx5_ftg_keygen_oper_dump(unit, ftg_keygen_md); if (ftg_keygen_md->save_op == FALSE) { rv = BCM_E_NONE; goto cleanup; } ft_group_id = ftg_keygen_md->ft_group_id; oper_info = &ftg_keygen_md->keydata_oper_info; rv = bcmi_esw_ft_group_extraction_mode_set(unit, 1, ft_group_id, oper_info->mode); if (BCM_SUCCESS(rv)) { rv = bcmi_esw_ft_group_extraction_mode_set(unit, 0, ft_group_id, oper_info->mode); } if (BCM_SUCCESS(rv) && (oper_info->skey_info != NULL)) { rv = bcmi_esw_ft_group_extraction_alu_info_set(unit, ft_group_id, 1, oper_info->num_skey_info, oper_info->skey_info); } if (BCM_SUCCESS(rv) && (oper_info->skey_ext_info != NULL)) { rv = bcmi_esw_ft_group_extraction_hw_info_set(unit, ft_group_id, 1, oper_info->skey_ext_count, oper_info->skey_ext_info); } if (BCM_SUCCESS(rv) && (oper_info->sdata_info != NULL)) { rv = bcmi_esw_ft_group_extraction_alu_info_set(unit, ft_group_id, 0, oper_info->num_sdata_info, oper_info->sdata_info); } if (BCM_SUCCESS(rv) && (oper_info->sdata_ext_info != NULL)) { rv = bcmi_esw_ft_group_extraction_hw_info_set(unit, ft_group_id, 0, oper_info->sdata_ext_count, oper_info->sdata_ext_info); } #ifdef BCM_FLOWTRACKER_V2_SUPPORT if ((soc_feature(unit, soc_feature_flex_flowtracker_ver_2)) && (BCM_SUCCESS(rv)) && (soc_feature(unit, soc_feature_flowtracker_ts_64_sw_war_support)) && (oper_info->sdata_ext_info != NULL)) { rv = _field_ftv2_ftg_vfp_opaqueid2_get(unit, ft_group_id, ftg_keygen_md); } #endif cleanup: ftg_keygen_md->state_rv = rv; ftg_keygen_md->prev_state = ftg_keygen_md->state; ftg_keygen_md->state = _FIELD_FT_GROUP_KEYGEN_END; return rv; } /* * Function: * _field_ftg_keygen_udf_qual_deinit * Purpose: * Clear up udf data qualifiers from qual cfg info db * Parameters: * unit - (IN) BCM device number. * db - (IN) Qual cfg info db * Returns: * BCM_E_PARAM - Invalid inputs. * BCM_E_MEMORY - Failed to allocate memory. * BCM_E_NONE - Success. */ STATIC int _field_ftg_keygen_udf_qual_deinit(int unit, bcmi_keygen_qual_cfg_info_db_t *db) { int ii = 0; int qual_id; uint16 udf_data_quals[] = { _bcmFieldQualifyData0, _bcmFieldQualifyData1, _bcmFieldQualifyData2, _bcmFieldQualifyData3, _bcmFieldQualifyData4, _bcmFieldQualifyData5, _bcmFieldQualifyData6, _bcmFieldQualifyData7, _bcmFieldQualifyData8, _bcmFieldQualifyData9, _bcmFieldQualifyData10, _bcmFieldQualifyData11, _bcmFieldQualifyData12, _bcmFieldQualifyData13, _bcmFieldQualifyData14, _bcmFieldQualifyData15 }; if (db == NULL) { return BCM_E_NONE; } for (ii = 0; ii < COUNTOF(udf_data_quals); ii++) { qual_id = udf_data_quals[ii]; if (db->qual_cfg_info[qual_id]) { BCMI_KEYGEN_FREE(db->qual_cfg_info[qual_id]->qual_cfg_arr); BCMI_KEYGEN_FREE(db->qual_cfg_info[qual_id]); } } return BCM_E_NONE; } /* * Function: * _field_hx5_ftg_keygen_end * Purpose: * Deallocate memories in FT Group Keygen metadata. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (INOUT) FT Group Keygen metadata. * Returns: * BCM_E_PARAM - Invalid inputs. * BCM_E_MEMORY - Failed to allocate memory. * BCM_E_NONE - Success. */ STATIC int _field_hx5_ftg_keygen_end(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { if (ftg_keygen_md->tracking_params_info != NULL) { sal_free(ftg_keygen_md->tracking_params_info); ftg_keygen_md->tracking_params_info = NULL; } if (ftg_keygen_md->flowtracker_checks != NULL) { sal_free(ftg_keygen_md->flowtracker_checks); ftg_keygen_md->flowtracker_checks = NULL; } if (ftg_keygen_md->skey_keygen_md.qual_info_arr != NULL) { sal_free(ftg_keygen_md->skey_keygen_md.qual_info_arr); ftg_keygen_md->skey_keygen_md.qual_info_arr = NULL; } if (ftg_keygen_md->sdata_keygen_md.qual_info_arr != NULL) { sal_free(ftg_keygen_md->sdata_keygen_md.qual_info_arr); ftg_keygen_md->sdata_keygen_md.qual_info_arr = NULL; } (void) bcmi_keygen_oper_free(unit, ftg_keygen_md->skey_keygen_md.num_parts, &ftg_keygen_md->skey_keygen_md.keygen_oper); (void) bcmi_keygen_oper_free(unit, ftg_keygen_md->sdata_keygen_md.num_parts, &ftg_keygen_md->sdata_keygen_md.keygen_oper); if (ftg_keygen_md->keydata_oper_info.sdata_info != NULL) { sal_free(ftg_keygen_md->keydata_oper_info.sdata_info); ftg_keygen_md->keydata_oper_info.sdata_info = NULL; } if (ftg_keygen_md->keydata_oper_info.skey_info != NULL) { sal_free(ftg_keygen_md->keydata_oper_info.skey_info); ftg_keygen_md->keydata_oper_info.skey_info = NULL; } if (ftg_keygen_md->keydata_oper_info.skey_ext_info != NULL) { sal_free(ftg_keygen_md->keydata_oper_info.skey_ext_info); ftg_keygen_md->keydata_oper_info.skey_ext_info = NULL; } if (ftg_keygen_md->keydata_oper_info.sdata_ext_info != NULL) { sal_free(ftg_keygen_md->keydata_oper_info.sdata_ext_info); ftg_keygen_md->keydata_oper_info.sdata_ext_info = NULL; } /* Clear up udf data qualifiers */ if (ftg_keygen_md->ft_info->flow_key_qual_cfg != NULL) { _field_ftg_keygen_udf_qual_deinit(unit, ftg_keygen_md->ft_info->flow_key_qual_cfg); } if (ftg_keygen_md->ft_info->flow_data_qual_cfg != NULL) { _field_ftg_keygen_udf_qual_deinit(unit, ftg_keygen_md->ft_info->flow_data_qual_cfg); } return (ftg_keygen_md->state_rv); } /* * Function: * _field_hx5_ftg_keygen_process * Purpose: * Gernerate session key, session data and alu data extractions * corresponding to FT Group tracking params and flowchecks. * Parameters: * unit - (IN) BCM device number. * ftg_keygen_md - (IN) FT Group Keygen metadata. * Returns: * BCM_E_XXX */ STATIC int _field_hx5_ftg_keygen_process(int unit, _field_ft_group_keygen_md_t *ftg_keygen_md) { int rv = BCM_E_NONE; do { switch(ftg_keygen_md->state) { case _FIELD_FT_GROUP_KEYGEN_START: rv = _field_hx5_ftg_keygen_initialize(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_START ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_ALLOC: rv = _field_hx5_ftg_keygen_cfg_alloc(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_ALLOC ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_ALU_QUAL_ADD: rv = _field_hx5_ftg_keygen_cfg_alu_qual_add(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_ALU_QUAL_ADD ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_FC_QUAL_ADD: rv = _field_hx5_ftg_keygen_cfg_flowcheck_qual_add(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_FC_QUAL_ADD ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_DATA_KEY_QUAL_ADD: rv = _field_hx5_ftg_keygen_cfg_data_key_qual_add(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_DATA_KEY_QUAL_ADD ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_DATA_QUAL_ADJUST: rv = _field_hx5_ftg_keygen_cfg_data_qual_adjust(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_DATA_QUAL_ADJUST ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_CFG_KEY_QUAL_ADJUST: rv = _field_hx5_ftg_keygen_cfg_key_qual_adjust(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_CFG_KEY_QUAL_ADJUST ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_DATA_OPER_EXTRACT: rv = _field_hx5_ftg_keygen_data_oper_extract(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_DATA_OPER_EXTRACT ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_KEY_OPER_EXTRACT: rv = _field_hx5_ftg_keygen_key_oper_extract(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_KEY_OPER_EXTRACT ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_DATA_OPER_PROCESS: rv = _field_hx5_ftg_keygen_data_oper_process(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_DATA_OPER_PROCESS ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_KEY_OPER_PROCESS: rv = _field_hx5_ftg_keygen_key_oper_process(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_KEY_OPER_PROCESS ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_MFT_DATA_PROCESS: rv = _field_hx5_ftg_keygen_mft_stage_process(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_MFT_DATA_PROCESS ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_EFT_DATA_PROCESS: rv = _field_hx5_ftg_keygen_eft_stage_process(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_EFT_DATA_PROCESS ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_OPER_SAVE: rv = _field_hx5_ftg_keygen_oper_save(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_OPER_SAVE ret=%d\r\n"), ftg_keygen_md->state_rv)); break; case _FIELD_FT_GROUP_KEYGEN_END: rv = _field_hx5_ftg_keygen_end(unit, ftg_keygen_md); LOG_DEBUG(BSL_LS_BCM_FP, (BSL_META_U(unit, "Completed state->" "_FIELD_FT_GROUP_KEYGEN_END ret=%d\r\n"), ftg_keygen_md->state_rv)); return rv; default: /* Not a valid case */ return rv; } } while(1); return rv; } /* * Function: * _bcm_field_ft_entry_traverse * Purpose: * Traverse fp entries in flowtracker stage and * call callback to process the entry. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracekr group. * cb_f - (IN) Callback function pointer * user_data1 - (IN) user data 1 * user_data2 - (IN) user data 2 * Returns: * BCM_E_XXX */ STATIC int _bcm_field_ftfp_entry_traverse(int unit, bcm_flowtracker_group_t id, _bcm_field_ft_entry_traverse_cb cb_f, void *user_data1, void *user_data2) { int rv = BCM_E_NONE; int eidx = 0; int entries = 0; _field_group_t *fg = NULL; _field_control_t *fc = NULL; bcm_field_entry_t *entry_ids = NULL; BCM_IF_ERROR_RETURN(_field_control_get(unit, &fc)); /* Iterate FTFP Groups */ for (fg = fc->groups; fg != NULL; fg = fg->next) { if ((fg->stage_id != _BCM_FIELD_STAGE_FLOWTRACKER) && (fg->stage_id != _BCM_FIELD_STAGE_AMFTFP) && (fg->stage_id != _BCM_FIELD_STAGE_AEFTFP)) { continue; } rv = bcm_esw_field_entry_multi_get(unit, fg->gid, 0, NULL, &entries); if (BCM_SUCCESS(rv)) { entry_ids = sal_alloc(entries * sizeof (bcm_field_entry_t), "Entry ID array"); if (entry_ids == NULL) { rv = BCM_E_MEMORY; break; } else { rv = bcm_esw_field_entry_multi_get(unit, fg->gid, entries, entry_ids, &entries); if (BCM_SUCCESS(rv)) { /* Iterate FTFP Entries */ for (eidx = 0; eidx < entries; eidx++) { /* Call callback */ rv = cb_f(unit, entry_ids[eidx], id, user_data1, user_data2); if (BCM_FAILURE(rv)) { break; } } } sal_free(entry_ids); entry_ids = NULL; } } } return (rv); } /* * Function: * _bcm_field_ft_qual_config_get * Purpose: * Get Qualifier config info from Qual Cfg Info Db. * Parameters: * unit - (IN) BCM device number. * qual_cfg_info_db - (IN) Qualifier cfg info db * qual - (IN) Qualifier * offset - (OUT) Offset of Qualifier in L0 Bus * Width - (OUT) Width of Qualifier in L0 Bus * Returns: * BCM_E_INTERNAL - Incoreect Input * BCM_E_NONE - Success. * Notes: * This function is only valid if all offets of qualifier * are consecutive and only one instance. */ STATIC int _bcm_field_ft_qual_config_get(int unit, bcmi_keygen_qual_cfg_info_db_t *db, bcm_field_qualify_t qual, uint32 *offset, uint32 *width) { uint8 num_chunks; uint8 chunk = 0; uint16 temp_width = 0; uint16 temp_offset = 0; bcmi_keygen_qual_offset_cfg_t *e_params = NULL; bcmi_keygen_qual_cfg_t *qual_cfg_arr = NULL; bcmi_keygen_qual_cfg_info_t *qual_cfg_info = NULL; if (db == NULL) { return BCM_E_INTERNAL; } qual_cfg_info = db->qual_cfg_info[qual]; qual_cfg_arr = qual_cfg_info->qual_cfg_arr; if (qual_cfg_arr == NULL) { return BCM_E_INTERNAL; } num_chunks = qual_cfg_arr->num_chunks; for (chunk = 0; chunk < num_chunks; chunk++) { e_params = &qual_cfg_arr->e_params[chunk]; if (chunk == 0) { temp_offset = e_params->offset; } temp_width += e_params->width; } *offset = temp_offset; *width = temp_width; return BCM_E_NONE; } /* * Function: * _field_hx5_ft_normalize_format_set * Purpose: * Set normalization format for given qualifier-pair. * Parameters: * unit - (IN) BCM device number. * index - (IN) Index in norm_qualifiers. * norm_qualifier - (IN) Normalization qualifiers list. * max_norm_commands - (IN) Maximum norm commands that can be * configured in hw memory. * norm_cmds_buf - (IN/OUT) Buffer for norm commands format. * valid_commands - (IN/OUT) valid commands in norm_cmds_bufs. * Returns: * BCM_E_XXX */ int _field_hx5_ft_normalize_format_set(int unit, bcm_flowtracker_tracking_param_info_t **norm_tracking_params_info, int max_norm_commands, uint32 *norm_cmds_buf, int *valid_commands) { uint32 comm_idx = 0; uint32 src_offset = 0; uint32 dst_offset = 0; uint32 src_width = 0; uint32 dst_width = 0; bcm_field_qualify_t src_qual; bcm_field_qualify_t dst_qual; _field_stage_t *stage_fc = NULL; bcm_flowtracker_tracking_param_type_t param; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; bcmi_keygen_qual_cfg_info_db_t *qual_cfg_info_db = NULL; if (*valid_commands >= max_norm_commands) { LOG_ERROR(BSL_LS_BCM_FP, (BSL_META_U(unit, "All Keys in tracking params" " of flowtracker group cannot be" " normalized\n\r"))); return BCM_E_CONFIG; } BCM_IF_ERROR_RETURN(_field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc)); map_db = stage_fc->ft_info->param_qual_map_db; qual_cfg_info_db = stage_fc->ft_info->flow_key_qual_cfg; /* Get Field Qualifiers */ param = norm_tracking_params_info[0]->param; src_qual = map_db->param_qual_map[param]->qual; param = norm_tracking_params_info[1]->param; dst_qual = map_db->param_qual_map[param]->qual; BCM_IF_ERROR_RETURN(_bcm_field_ft_qual_config_get(unit, qual_cfg_info_db, src_qual, &src_offset, &src_width)); BCM_IF_ERROR_RETURN(_bcm_field_ft_qual_config_get(unit, qual_cfg_info_db, dst_qual, &dst_offset, &dst_width)); /* Validate alignemnt */ if (((src_offset % 16) != 0) || ((dst_offset % 16) != 0) || ((src_width % 16) != 0) || (dst_width != src_width) || (src_width == 0) || (dst_width == 0)) { return BCM_E_CONFIG; } src_offset /= 16; dst_offset /= 16; /* Formula for size is (n + 1)*2B */ src_width = (src_width - 1) / 16; comm_idx = *valid_commands; soc_format_field32_set(unit, BSK_NORMALIZE_COMMAND_FORMATfmt, &norm_cmds_buf[comm_idx], NORMALIZE_ENABLEf, 1); soc_format_field32_set(unit, BSK_NORMALIZE_COMMAND_FORMATfmt, &norm_cmds_buf[comm_idx], NORMALIZE_SRC_START_OFFSETf, src_offset); soc_format_field32_set(unit, BSK_NORMALIZE_COMMAND_FORMATfmt, &norm_cmds_buf[comm_idx], NORMALIZE_DST_START_OFFSETf, dst_offset); soc_format_field32_set(unit, BSK_NORMALIZE_COMMAND_FORMATfmt, &norm_cmds_buf[comm_idx], NORMALIZE_SIZEf, src_width); *valid_commands = comm_idx + 1; return BCM_E_NONE; } /* * Function: * _field_hx5_ft_normalize_controls_set * Purpose: * Set normalize controls of FTFP policy table. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id * policy_mem - (IN) Policy Memory * enable - (IN) Normalization Enable/Disable * data_buf - (IN/OUT) Policy memory buffer * Returns: * BCM_E_XXX */ int _field_hx5_ft_normalize_controls_set(int unit, bcm_flowtracker_group_t id, soc_mem_t policy_mem, uint32 enable, uint32 *data_buf) { int idx = 0; int rv = BCM_E_NONE; int valid_commands = 0; int num_tracking_params = 0; uint32 norm_cmds_buf[4] = {0}; bcm_flowtracker_tracking_param_info_t *tracking_params_info = NULL; bcm_flowtracker_tracking_param_info_t *norm_tracking_params_info[BCMI_FT_GROUP_NORM_TRACKING_PARAMS] = {NULL}; /* Normalize Commands */ soc_field_t normalize_cmds_f[] = { NORMALIZE_0_COMMANDf, NORMALIZE_1_COMMANDf, NORMALIZE_2_COMMANDf, NORMALIZE_3_COMMANDf }; /* If enable=FALSE, reset Normalize commands */ if (enable == 0) { for (idx = 0; idx < COUNTOF(normalize_cmds_f); idx++) { if (SOC_MEM_FIELD_VALID(unit, policy_mem, normalize_cmds_f[idx])) { soc_mem_field_set(unit, policy_mem, (void *) data_buf, normalize_cmds_f[idx], &norm_cmds_buf[idx]); } } goto cleanup; } /* Get number of tracking params from group template */ rv = bcm_esw_flowtracker_group_tracking_params_get(unit, id, 0, NULL, &num_tracking_params); BCMI_IF_ERROR_CLEANUP(rv); /* Allocate memory for tracking params info */ _FP_XGS3_ALLOC(tracking_params_info, (num_tracking_params * \ sizeof(bcm_flowtracker_tracking_param_info_t)), "tracking params info"); if (tracking_params_info == NULL) { rv = BCM_E_MEMORY; BCMI_IF_ERROR_CLEANUP(rv); } /* Read tracking params info */ rv = bcm_esw_flowtracker_group_tracking_params_get(unit, id, num_tracking_params, &tracking_params_info[0], &num_tracking_params); BCMI_IF_ERROR_CLEANUP(rv); /* Get tracking params for normalization */ rv = bcmi_ft_group_norm_tracking_params_info_get(unit, id, &norm_tracking_params_info[0]); BCMI_IF_ERROR_CLEANUP(rv); /* Normalize if both param in the pair are present */ for (idx = 0; idx < BCMI_FT_GROUP_NORM_TRACKING_PARAMS; idx += 2) { if ((norm_tracking_params_info[idx] != NULL) && (norm_tracking_params_info[idx + 1] != NULL)) { rv = _field_hx5_ft_normalize_format_set(unit, &norm_tracking_params_info[idx], COUNTOF(normalize_cmds_f), norm_cmds_buf, &valid_commands); BCMI_IF_ERROR_CLEANUP(rv); } } /* Set to policy table */ for (idx = 0; idx < valid_commands; idx++) { if (SOC_MEM_FIELD_VALID(unit, policy_mem, normalize_cmds_f[idx])) { soc_mem_field_set(unit, policy_mem, (void *) data_buf, normalize_cmds_f[idx], &norm_cmds_buf[idx]); } } cleanup: if (tracking_params_info != NULL) { sal_free(tracking_params_info); } return rv; } /* * Function: * _field_ftfp_entry_control_set * Purpose: * Apply flowtracker group control to given entry if associated * action is given flowtracker group. * Parameters: * unit - (IN) BCM device number. * entry - (IN) Field entry. * id - (IN) Flowtracker group Id * user_data1 - (IN) user data 1 * user_data2 - (IN) user data 2 * Returns: * BCM_E_PARAM - If input parameters are not valid * BCM_E_MEMORY - If Failed to allocate required memory * BCM_E_NONE - Success. */ STATIC int _field_ftfp_entry_control_set(int unit, bcm_field_entry_t entry, bcm_flowtracker_group_t id, void *user_data1, void *user_data2) { int rv = BCM_E_NONE; int tcam_idx = 0; int param = 0; uint32 val = 0, val2 = 0; uint32 ft_group_id_set = 0; uint32 action_ft_set = 0; uint32 ent_action_ft = 0; uint32 action_new_learn_set = 0; uint32 ent_action_new_learn = 0; uint32 cur_param = 0; _field_action_t *fa = NULL; _field_entry_t *f_ent = NULL; soc_field_t field = INVALIDf; soc_field_t field2 = INVALIDf; soc_mem_t tcam_mem = INVALIDm; soc_mem_t policy_mem = INVALIDm; bcm_flowtracker_group_control_type_t control_type; bcm_flowtracker_group_t ent_flow_group_id = -1; uint32 data_buf[SOC_MAX_MEM_FIELD_WORDS] = {0}; if ((user_data1 == NULL) || (user_data2 == NULL)) { return BCM_E_PARAM; } control_type = *((bcm_flowtracker_group_control_type_t *) user_data1); param = *((int *)user_data2); FP_LOCK(unit); rv = _field_entry_get(unit, entry, _FP_ENTRY_PRIMARY, &f_ent); if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return (rv); } /* Loop through all actions */ for (fa = f_ent->actions; (fa != NULL) && (fa->flags & _FP_ACTION_VALID); fa = fa->next) { switch(fa->action) { case bcmFieldActionFlowtrackerGroupId: if (!(fa->flags & _FP_ACTION_DIRTY)) { ft_group_id_set = TRUE; ent_flow_group_id = fa->param[0]; } break; case bcmFieldActionFlowtrackerEnable: if (!(fa->flags & _FP_ACTION_DIRTY)) { action_ft_set = TRUE; ent_action_ft = fa->param[0]; } break; case bcmFieldActionFlowtrackerNewLearnEnable: if (!(fa->flags & _FP_ACTION_DIRTY)) { action_new_learn_set = 1; ent_action_new_learn = fa->param[0]; } break; default: break; } } if ((ft_group_id_set == FALSE) || (ent_flow_group_id != id)) { FP_UNLOCK(unit); return rv; } /* Get Policy Index */ rv = _bcm_field_entry_tcam_idx_get(unit, f_ent, &tcam_idx); if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return rv; } /* Get Policy Mem */ rv = _bcm_field_th_tcam_policy_mem_get(unit, f_ent, &tcam_mem, &policy_mem); if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return rv; } rv = soc_mem_read(unit, policy_mem, MEM_BLOCK_ANY, tcam_idx, data_buf); if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return rv; } /* Supported ft_group Controls are DO_NOT_FT and LEARN_DISABLE */ switch(control_type) { case bcmFlowtrackerGroupControlFlowtrackerEnable: field = DO_NOT_FTf; /* if Field Action is present, it takes priority. */ if (action_ft_set == TRUE) { val = (ent_action_ft) ? 0 : 1; } else { val = (param) ? 0 : 1; } break; case bcmFlowtrackerGroupControlNewLearnEnable: field = LEARN_DISABLEf; /* if Field Action is present, it takes priority. */ if (action_new_learn_set == TRUE) { val = (ent_action_new_learn) ? 0 : 1; } else { val = (param) ? 0 : 1; } break; case bcmFlowtrackerGroupControlFlowDirection: field = BIDIRECTIONAL_FLOWf; val= ((param == bcmFlowtrackerFlowDirectionBidirectional) ? 1 : 0); field2 = KMAP_CONTROL_1_2_PROFILE_IDXf; val2 = 0; rv = _field_hx5_ft_normalize_controls_set(unit, id, policy_mem, val, data_buf); break; case bcmFlowtrackerGroupControlUdpFlowDirection: field = BIDIRECTIONAL_FLOWf; val= ((param == bcmFlowtrackerFlowDirectionBidirectional) ? 1 : 0); field2 = KMAP_CONTROL_1_2_PROFILE_IDXf; val2 = 1; rv = _field_hx5_ft_normalize_controls_set(unit, id, policy_mem, val, data_buf); break; default: rv = BCM_E_PARAM; break; } if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return rv; } if (SOC_MEM_FIELD_VALID(unit, policy_mem, field)) { cur_param = soc_mem_field32_get(unit, policy_mem, data_buf, field); if (cur_param != val) { soc_mem_field32_set(unit, policy_mem, data_buf, field, val); } } if (SOC_MEM_FIELD_VALID(unit, policy_mem, field2)) { cur_param = soc_mem_field32_get(unit, policy_mem, data_buf, field2); if (cur_param != val2) { soc_mem_field32_set(unit, policy_mem, data_buf, field2, val2); } } rv = soc_mem_write(unit, policy_mem, MEM_BLOCK_ALL, tcam_idx, data_buf); FP_UNLOCK(unit); return rv; } /* * Function: * _field_ftfp_entry_action_stale_set * Purpose: * Mark flowtracker group id action in ftfp entries as * staled out. * Parameters: * unit - (IN) BCM device number. * entry - (IN) Field entry. * id - (IN) Flowtracker group Id * user_data1 - (IN) user data 1 * user_data2 - (IN) user data 2 * Returns: * BCM_E_PARAM - If input parameters are not valid * BCM_E_NONE - Success. * BCM_E_XXX */ STATIC int _field_ftfp_entry_action_stale_set(int unit, bcm_field_entry_t entry, bcm_flowtracker_group_t id, void *user_data1, void *user_data2) { int rv = BCM_E_NONE; _field_entry_t *f_ent = NULL; FP_LOCK(unit); rv = _field_entry_get(unit, entry, _FP_ENTRY_PRIMARY, &f_ent); if (BCM_FAILURE(rv)) { FP_UNLOCK(unit); return (rv); } rv = _bcm_field_hx5_ft_actions_hw_free(unit, f_ent, _FP_ACTION_HW_FREE | _BCM_FIELD_ACTION_REF_STALE); FP_UNLOCK(unit); return rv; } /* Public Interfaces */ /* * Function: * _bcm_field_ft_alu_data_config_get * Purpose: * Get ALU Data config info * Parameters: * unit - (IN) BCM device number. * id - (IN) flowtracker group id. * alu_data - (IN) Alu Data param * offset - (OUT) Offset in ALU Data vector. * width - (OUT) Number of bits in ALU Data vector. * Returns: * BCM_E_NOT_FOUND - If given alu_data is not found. * BCM_E_NONE */ int _bcm_field_ft_alu_data_config_get(int unit, bcm_flowtracker_group_t id, _bcm_field_ft_alu_data_t alu_data, int *offset, int *width) { int rv = BCM_E_NONE; int index = 0; int num_alu_data = 0; uint8 found = FALSE; uint16 param = 0; _field_ft_tracking_alu_data_info_t *alu_data_info = NULL; alu_data_info = &_field_ft_alu_data_info_tcp_control[0]; num_alu_data = COUNTOF(_field_ft_alu_data_info_tcp_control); for (index = 0; index < num_alu_data; index++) { param = alu_data_info[index].param; if (param == alu_data) { found = TRUE; if (offset != NULL) { *offset = alu_data_info[index].extract_pos; } if (width != NULL) { *width = alu_data_info[index].width; } } } if (found == FALSE) { rv = BCM_E_NOT_FOUND; } return rv; } /* * Function: * _bcm_field_ft_group_tracking_info_process * Purpose: * Process FT group tracking information and update FT group * database, if required * Parameters: * unit - (IN) BCM device number. * id - (IN) flowtracker group id. * save_output- (IN) TRUE if output is required to be saved to * FT Group DB. * Returns: * BCM_E_XXX */ int _bcm_field_ft_group_tracking_info_process(int unit, bcm_flowtracker_group_t id, uint8 save_output) { _field_ft_group_keygen_md_t ftg_keygen_md; sal_memset(&ftg_keygen_md, 0, sizeof(_field_ft_group_keygen_md_t)); ftg_keygen_md.state_rv = BCM_E_NONE; ftg_keygen_md.ft_group_id = id; ftg_keygen_md.state = _FIELD_FT_GROUP_KEYGEN_START; ftg_keygen_md.prev_state = _FIELD_FT_GROUP_KEYGEN_START; ftg_keygen_md.save_op = save_output; return _field_hx5_ftg_keygen_process(unit, &ftg_keygen_md); } /* * Function: * _bcm_field_ft_group_extraction_clear * Purpose: * Cleanup FT group tracking params extraction information * from FT group database * Parameters: * unit - (IN) BCM device number. * id - (IN) flowtracker group id. * Returns: * BCM_E_XXX */ int _bcm_field_ft_group_extraction_clear(int unit, bcm_flowtracker_group_t id) { int rv = BCM_E_NONE; /* Clear session key params extraction info */ rv = bcmi_esw_ft_group_extraction_alu_info_set(unit, id, 1, 0, NULL); BCM_IF_ERROR_RETURN(rv); /* Clear session key hw extractors info */ rv = bcmi_esw_ft_group_extraction_hw_info_set(unit, id, 1, 0, NULL); BCM_IF_ERROR_RETURN(rv); /* Clear session data params extraction info */ rv = bcmi_esw_ft_group_extraction_alu_info_set(unit, id, 0, 0, NULL); BCM_IF_ERROR_RETURN(rv); /* Clear session data hw extractors info */ rv = bcmi_esw_ft_group_extraction_hw_info_set(unit, id, 0, 0, NULL); return rv; } /* * Function: * _bcm_field_ft_group_control_set * Purpose: * Apply flowtracker group controls to each entry in which * action is given flowtracker group.. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker group * control_type- (IN) control to apply * param - (IN) Parameter associated with control * Returns: * BCM_E_PARAM - Null field stage control structure. * BCM_E_NONE - Success. */ int _bcm_field_ft_group_control_set(int unit, bcm_flowtracker_group_t id, bcm_flowtracker_group_control_type_t control_type, int param) { return _bcm_field_ftfp_entry_traverse(unit, id, _field_ftfp_entry_control_set, (void *) &control_type, (void *) &param); } /* * Function: * _bcm_field_ft_group_invalidate * Purpose: * Mark flowtracker group Id action in ftfp entries * stale. * Parameters: * unit - (IN) BCM device number. * Returns: * BCM_E_XXX */ int _bcm_field_ft_group_invalidate(int unit) { return _bcm_field_ftfp_entry_traverse(unit, -1, _field_ftfp_entry_action_stale_set, NULL, NULL); } /* * Function: * _bcm_field_ft_tracking_param_range_get * Purpose: * Returns minimum and maximum values of tracking params. * Parameters: * unit - (IN) BCM device number. * param - (IN) Tracking param. * min_value - (OUT) Minimum value. * max_value - (OUT) Maximum value. * Returns: * BCM_E_XXX */ int _bcm_field_ft_tracking_param_range_get(int unit, bcm_flowtracker_tracking_param_type_t param, uint16 custom_id, int *num_bits, uint32 *min_value, uint32 *max_value) { int rv = BCM_E_NONE; uint16 max_bits = 0; bcmi_keygen_cfg_t keygen_cfg; _field_stage_t *stage_fc = NULL; _field_ft_info_t *ft_info = NULL; bcm_flowtracker_udf_info_t param_udf_info; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; if (param >= _FIELD_FT_TRACKING_PARAM_MAX) { return BCM_E_PARAM; } rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); BCM_IF_ERROR_RETURN(rv); ft_info = stage_fc->ft_info; map_db = ft_info->param_qual_map_db; pq_map = map_db->param_qual_map[param]; if (pq_map == NULL) { return BCM_E_PARAM; } /* Get number of bits required to represent qualifier. */ if (!(pq_map->flags & _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED)) { if ((pq_map->db_ft_type_bmp & (BCMI_FT_TYPE_F_IFT | BCMI_FT_TYPE_F_AIFT)) && (param != bcmFlowtrackerTrackingParamTypeIngressDelay)) { keygen_cfg.qual_cfg_info_db = ft_info->flow_key_qual_cfg; rv = bcmi_keygen_qual_cfg_max_size_get(unit, &keygen_cfg, pq_map->qual, &max_bits); BCM_IF_ERROR_RETURN(rv); } else { max_bits = pq_map->width; } } /* UDF tracking param */ if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = bcm_esw_flowtracker_udf_tracking_param_get(unit, 0, param, custom_id, &param_udf_info); BCM_IF_ERROR_RETURN(rv); max_bits = param_udf_info.width; } if (min_value != NULL) { *min_value = 0; } if (max_value != NULL) { if ((max_bits == 0) || (max_bits == 32)) { *max_value = 0xFFFFFFFF; } else { *max_value = (1 << max_bits) - 1; } } if (num_bits != NULL) { *num_bits = max_bits; } return rv; } /* * Function: * _bcm_field_ft_tracking_param_type_get * Purpose: * Returns tracking param type if supported. * Parameters: * unit - (IN) BCM device number. * param - (IN) Tracking param. * flags - (IN) Tracking param flags. * ft_type - (OUT) Tracking param ft type. * Notes: * This is a utility api to fetch ft_type of tracking * param passed as input. Any tracking param should * belong to either IFT/MFT/EFT stage currently supported. * Returns: * BCM_E_XXX */ int _bcm_field_ft_tracking_param_type_get(int unit, bcm_flowtracker_tracking_param_type_t param, uint16 custom_id, uint32 flags, uint16 *ft_type_bmp) { int rv = BCM_E_NONE; _field_stage_t *stage_fc = NULL; _field_ft_info_t *ft_info = NULL; bcm_flowtracker_udf_info_t param_udf_info; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; const char *plist[] = BCM_FT_TRACKING_PARAM_STRINGS; const char *aludatalist[] = _BCM_FIELD_FT_ALU_DATA_STRINGS; /* Input Param Check */ if (param >= _FIELD_FT_TRACKING_PARAM_MAX || ft_type_bmp == NULL) { return BCM_E_PARAM; } /* Retreive flowtracker stage */ rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); BCM_IF_ERROR_RETURN(rv); /* Retreive tracking param db */ ft_info = stage_fc->ft_info; map_db = ft_info->param_qual_map_db; pq_map = map_db->param_qual_map[param]; /* Return error if not present in db */ if (pq_map == NULL) { if (param < _FIELD_FT_TRACKING_ELEMENT_TYPE_MAX) { LOG_ERROR(BSL_LS_BCM_FLOWTRACKER, (BSL_META_U(unit, "Tracking param %s is not available\n"), plist[param])); } else if (param < _FIELD_FT_TRACKING_PARAM_MAX) { LOG_ERROR(BSL_LS_BCM_FLOWTRACKER, (BSL_META_U(unit, "Tracking param %s is not available\n"), aludatalist[param - _FIELD_FT_TRACKING_ELEMENT_TYPE_MAX])); } return BCM_E_PARAM; } /* UDF tracking param */ if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { rv = bcm_esw_flowtracker_udf_tracking_param_get(unit, 0, param, custom_id, &param_udf_info); if (BCM_FAILURE(rv)) { if (param < _FIELD_FT_TRACKING_ELEMENT_TYPE_MAX) { LOG_ERROR(BSL_LS_BCM_FLOWTRACKER, (BSL_META_U(unit, "UDF Tracking param %s(%d) not configured\n"), plist[param], custom_id)); } return rv; } if ((!(flags & BCM_FLOWTRACKER_TRACKING_PARAM_TYPE_KEY)) && (param_udf_info.width > 32)) { if (param < _FIELD_FT_TRACKING_ELEMENT_TYPE_MAX) { LOG_ERROR(BSL_LS_BCM_FLOWTRACKER, (BSL_META_U(unit, "Tracking param %s(%d) exceeds supported" " width\n"), plist[param], custom_id)); } return BCM_E_PARAM; } } /* Return ft type of provided tracking param */ *ft_type_bmp = pq_map->db_ft_type_bmp; return rv; } /* * Function: * _bcm_field_ft_session_profiles_install * Purpose: * Install session profiles for ftfp policy * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id. * profiles - (OUT) Session Profiles. * Returns: * BCM_E_XXX */ int _bcm_field_ft_session_profiles_install( int unit, bcm_flowtracker_group_t id) { int rv = BCM_E_NONE; bcmi_ft_session_profiles_t profiles; #if defined(BCM_FLOWTRACKER_V3_SUPPORT) if ((BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateMmu) || (BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateEgress)) { return BCM_E_NONE; } #endif sal_memset(&profiles, 0, sizeof (bcmi_ft_session_profiles_t)); rv = _field_hx5_ft_session_profiles_install(unit, id, &profiles); if (BCM_SUCCESS(rv)) { rv = bcmi_ft_group_ftfp_profiles_set(unit, id, &profiles); } if (BCM_SUCCESS(rv)) { rv = bcmi_ft_group_session_key_type_set(unit, id, profiles.session_key_profile_idx - 1); } return rv; } /* * Function: * _bcm_field_ft_session_profiles_uninstall * Purpose: * Un-install session profiles for ftfp policy * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id. * profiles - (IN) Session Profiles. * Returns: * BCM_E_XXX */ int _bcm_field_ft_session_profiles_uninstall( int unit, bcm_flowtracker_group_t id) { int rv = BCM_E_NONE; bcmi_ft_session_profiles_t profiles; #if defined(BCM_FLOWTRACKER_V3_SUPPORT) if ((BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateMmu) || (BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateEgress)) { return BCM_E_NONE; } #endif sal_memset(&profiles, 0, sizeof (bcmi_ft_session_profiles_t)); rv = bcmi_ft_group_ftfp_profiles_get(unit, id, &profiles); BCM_IF_ERROR_RETURN(rv); return _field_hx5_ft_session_profiles_remove(unit, id, &profiles); } /* * Function: * _bcm_field_ft_session_profiles_recover * Purpose: * Recover session profiles indices. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id. * Returns: * BCM_E_XXX */ int _bcm_field_ft_session_profiles_recover(int unit, bcm_flowtracker_group_t id) { bcmi_ft_session_profiles_t profiles; #if defined(BCM_FLOWTRACKER_V3_SUPPORT) if ((BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateMmu) || (BCMI_FT_GROUP_TYPE_GET(id) == bcmFlowtrackerGroupTypeAggregateEgress)) { return BCM_E_NONE; } #endif BCM_IF_ERROR_RETURN(bcmi_ft_group_ftfp_profiles_get(unit, id, &profiles)); BCM_IF_ERROR_RETURN(_field_hx5_ft_session_profiles_reference( unit, id, &profiles)); if (profiles.session_key_profile_idx != 0) { BCM_IF_ERROR_RETURN(bcmi_ft_group_session_key_type_set(unit, id, profiles.session_key_profile_idx - 1)); } return BCM_E_NONE; } /* * Function: * _bcm_field_ft_group_checkbmp_get * Purpose: * Get flowtracker check in ALU16 bitmap. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id. * num_checks - (IN) Number of flowchecks. * check_list - (IN) List of Flowchecks * check_bmp_data - (OUT) Data bitmap * check_bmp_mask - (OUT) Mask bitmap. * Returns: * BCM_E_XXX */ int _bcm_field_ft_group_checkbmp_get( int unit, bcm_flowtracker_group_t id, uint32 num_checks, bcm_field_flowtrackercheck_t *check_list, uint32 *check_bmp_data, uint32 *check_bmp_mask) { return bcmi_esw_ft_group_checks_bitmap_get(unit, id, num_checks, check_list, check_bmp_data, check_bmp_mask); } /* * Function: * _bcm_field_ft_group_checklist_get * Purpose: * Get list of flowtracker check from ALU16 bitmap. * Parameters: * unit - (IN) BCM device number. * id - (IN) Flowtracker Group Id. * check_bmp_data - (IN) Data bitmap. * check_bmp_mask - (IN) Mask bitmap. * num_checks - (IN) Number of flowchecks. * check_list - (OUT) List of Flowchecks. * actual_num_checks - (OUT) actual number of flowchecks. * Returns: * BCM_E_XXX */ int _bcm_field_ft_group_checklist_get( int unit, bcm_flowtracker_group_t id, uint32 check_bmp_data, uint32 check_bmp_mask, uint32 num_checks, bcm_field_flowtrackercheck_t *check_list, uint32 *actual_num_checks) { return bcmi_esw_ft_group_checks_list_get(unit, id, check_bmp_data, check_bmp_mask, num_checks, check_list, actual_num_checks); } #if defined(BCM_FLOWTRACKER_V2_SUPPORT) /* * Function: * _field_ft_mmu_tracking_param_qual_map_db_init * Purpose: * Prepare database for mmu tracking params and corresponding * qualifiers. * Parameters: * unit - (IN) BCM device number. * map_db - (IN/OUT) param-qualifier map * Returns: * BCM_E_XXX */ STATIC int _field_ft_mmu_tracking_param_qual_map_db_init(int unit, _field_ft_tracking_param_qual_map_db_t *map_db) { int rv = BCM_E_NONE; int offset = 0; uint16 ft_type_bmp = 0; uint32 flags = 0, len = 0; soc_format_t fmt = INVALIDfmt; soc_field_info_t *field_info = NULL; _FP_FT_TRACKING_PARAM_QUAL_MAP_DECL; /* MFT Session Bus */ fmt = MFT_SESSION_DATA_BUSfmt; field_info = soc_format_fieldinfo_get(unit, fmt, MMU_PERC_FILL_LEVELf); if (field_info == NULL) { return BCM_E_NONE; } offset = field_info->bp; flags = _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; ft_type_bmp = (BCMI_FT_TYPE_F_MFT | BCMI_FT_TYPE_F_AMFT); fmt = MMU_MFT_PERC_FILL_LEVELfmt; /* Enable congestion level tracking only if congestion feature * is enabled which in turn is set based on * OTP bit (CONGESTION_TRACKING_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_mmu_congestion_level)) { /* Percentage fill-level of port-PG min guarantee space. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTPG_MIN_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTPG_MIN_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPGMinCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of port-PG shared space. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTPG_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTPG_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPGSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of port-SP ?min guarantee? space. Report the service pool fill level for one of the four SPs, that the current packet belongs to. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTSP_MIN_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTSP_MIN_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPoolMinCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of port-SP shared space. Report the service pool fill level for one of the four SPs, that the current packet belongs to. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTSP_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTSP_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPoolSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of global-SP shared space. Report the service pool fill level for one of the four SPs, that the current packet belongs to. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_POOL_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_POOL_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPoolSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of PG headroom space. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTPG_HDRM_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTPG_HDRM_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPGHeadroomCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of port-SP headroom space. Report the service pool fill level for one of the four SPs, that the current packet belongs to. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_PTSP_HDRM_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_PTSP_HDRM_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPortPoolHeadroomCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of global headroom space. This is valid for UC & MC. */ if (soc_format_field_valid(unit, fmt, THDI_GLOBAL_HDRM_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDI_GLOBAL_HDRM_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngGlobalHeadroomCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the Unicast & Multicast buffer combined, unless separate service pools are used for UC and MC traffic types. */ if (soc_format_field_valid(unit, fmt, THDO_POOL_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDO_POOL_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrPoolSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the current UC queue minimum guarantee space. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 0 (UC). Also, THDR_DB_Q_MIN_FILLf Percentage fill-level of the current RQE queue (for MC) minimum guarantee space. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC). */ if (soc_format_field_valid(unit, fmt, THDU_Q_MIN_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDU_Q_MIN_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrQueueMinCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the current UC queue shared space. Depending of the color of the packet, provide the percentage fill of the queue shared count, as compared to the green, yellow and red drop-limits of the queue. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 0 (UC). Also, THDR_DB_Q_SHR_FILLf Percentage fill-level of the current RQE queue shared space. Depending of the color of the packet, provide the percentage fill of the queue shared count, as compared to the green, yellow and red drop-limits of the queue. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC). */ if (soc_format_field_valid(unit, fmt, THDU_Q_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDU_Q_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrQueueSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the current UC queue-group minimum guarantee space. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 0 (UC). Also, THDR_DB_POOL_SHR_FILLf Percentage fill-level of the global buffer pool computed based on THDR_DB_POOL limit. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC). */ if (soc_format_field_valid(unit, fmt, THDU_QGRP_MIN_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDU_QGRP_MIN_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrQueueGroupMinCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the current UC queue-group shared space. Similar to the UC queue shared fill-level. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 0 (UC). Also, THDR_QE_Q_MIN_FILLf Percentage fill-level of the current RQE queue (for MC) minimum guarantee space. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC). */ if (soc_format_field_valid(unit, fmt, THDU_QGRP_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDU_QGRP_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrQueueGroupSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the current UC Port-SP shared space. Similar to the UC queue shared fill-level. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 0 (UC). Also, THDR_QE_Q_SHR_FILLf Percentage fill-level of the current RQE queue shared space. Depending of the color of the packet, provide the percentage fill of the queue shared count, as compared to the green, yellow and red drop-limits of the queue. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC). */ if (soc_format_field_valid(unit, fmt, THDU_PORTSP_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDU_PORTSP_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrPortPoolSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of the RQE Qentry FIFO, which indicates the number of MC packet burst that the chip can absorb. Valid when MMU_MFT_PKT_FLAG.PKT_UC_MC is 1 (MC) */ if (soc_format_field_valid(unit, fmt, THDR_QE_POOL_SHR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, THDR_QE_POOL_SHR_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrRQEPoolSharedCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* Percentage fill-level of free cell pointer pool. Valid for all pakcet types. */ if (soc_format_field_valid(unit, fmt, CFAP_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, CFAP_FILLf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeCFAPCongestionLevel, 0, offset + field_info->bp, field_info->len, ft_type_bmp); } } /* MMU aggregate fill-level percentage based on various fill-levels per packet type (UC or MC) */ if (soc_format_field_valid(unit, fmt, MMU_AGGR_FILLf)) { field_info = soc_format_fieldinfo_get(unit, fmt, MMU_AGGR_FILLf); if (field_info != NULL) { if ((SOC_IS_HURRICANE4(unit)) && (field_info->len == 16)) { len = field_info->len - 8; } else { len = field_info->len; } _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUCongestionLevel, 0, field_info->bp, len, ft_type_bmp); } } } fmt = MFT_SESSION_DATA_BUSfmt; field_info = soc_format_fieldinfo_get(unit, fmt, MFT_IPIPE_LATE_STAGE_DATAf); if (field_info == NULL) { return BCM_E_INTERNAL; } offset = field_info->bp; fmt = IPIPE_LATE_STAGE_DATAfmt; #if 0 /* ECMP Member Id Level 1 */ if (soc_format_field_valid(unit, fmt, ECMP_MEMBER_ID_LEVEL1f)) { field_info = soc_format_fieldinfo_get(unit, fmt, ECMP_MEMBER_ID_LEVEL1f); len = soc_format_field_length(unit, fmt, ECMP_MEMBER_ID_LEVEL1_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeECMPMemberLevel1, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } /* ECMP Member Level 2 */ if (soc_format_field_valid(unit, fmt, ECMP_MEMBER_ID_LEVEL2f)) { field_info = soc_format_fieldinfo_get(unit, fmt, ECMP_MEMBER_ID_LEVEL2f); len = soc_format_field_length(unit, fmt, ECMP_MEMBER_ID_LEVEL2_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeECMPMemberLevel2, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } #endif /* Enable load balancing tracking params based on feature * which in turn is set based on OTP bit (ECMP_LAG_TRACKING_DISABLE). */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_load_balancing)) { /* ECMP Group Id Level 1*/ if (soc_format_field_valid(unit, fmt, ECMP_GROUP_ID_LEVEL1f)) { field_info = soc_format_fieldinfo_get(unit, fmt, ECMP_GROUP_ID_LEVEL1f); len = soc_format_field_length(unit, fmt, ECMP_GROUP_ID_LEVEL1_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeECMPGroupIdLevel1, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } /* ECMP Group Id Level 2 */ if (soc_format_field_valid(unit, fmt, ECMP_GROUP_ID_LEVEL2f)) { field_info = soc_format_fieldinfo_get(unit, fmt, ECMP_GROUP_ID_LEVEL2f); len = soc_format_field_length(unit, fmt, ECMP_GROUP_ID_LEVEL2_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeECMPGroupIdLevel2, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } /* Trunk Member Id */ if (soc_format_field_valid(unit, fmt, TRUNK_MEMBER_IDf)) { field_info = soc_format_fieldinfo_get(unit, fmt, TRUNK_MEMBER_IDf); len = soc_format_field_length(unit, fmt, TRUNK_MEMBER_ID_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTrunkMemberId, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } /* Trunk Group Id */ if (soc_format_field_valid(unit, fmt, TRUNK_GROUP_IDf)) { field_info = soc_format_fieldinfo_get(unit, fmt, TRUNK_GROUP_IDf); len = soc_format_field_length(unit, fmt, TRUNK_GROUP_ID_RESERVEDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeTrunkGroupId, 0, offset + field_info->bp, len + field_info->len, ft_type_bmp); } } } fmt = MFT_SESSION_DATA_BUSfmt; /* MMU Queue Id */ if (soc_format_field_valid(unit, fmt, QUEUE_IDf)) { field_info = soc_format_fieldinfo_get(unit, fmt, QUEUE_IDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUQueueId, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* MMU Queue Group Id */ if (soc_format_field_valid(unit, fmt, QGIDf)) { field_info = soc_format_fieldinfo_get(unit, fmt, QGIDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUQueueGroupId, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* Packet Tos */ if (soc_format_field_valid(unit, fmt, PACKET_TOSf)) { field_info = soc_format_fieldinfo_get(unit, fmt, PACKET_TOSf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUPacketTos, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* Ingress Port */ if (soc_format_field_valid(unit, fmt, INGRESS_PORTf)) { field_info = soc_format_fieldinfo_get(unit, fmt, INGRESS_PORTf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngPort, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* Enable drop reason code tracking params based on feature * which in turn is set based on * OTP bit (DROP_ANALYSIS_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_drop_code)) { /* Drop Reason Group Id Vector */ ft_type_bmp = (BCMI_FT_TYPE_F_MFT | BCMI_FT_TYPE_F_AMFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIngDropReasonGroupIdVector, 0, 240, 16, ft_type_bmp); } cleanup: return rv; } /* * Function: * _field_ft_egr_tracking_param_qual_map_db_init * Purpose: * Prepare database for Egress tracking params and corresponding * qualifiers. * Parameters: * unit - (IN) BCM device number. * map_db - (IN/OUT) param-qualifier map * Returns: * BCM_E_XXX */ STATIC int _field_ft_egr_tracking_param_qual_map_db_init(int unit, _field_ft_tracking_param_qual_map_db_t *map_db) { int rv = BCM_E_NONE; uint16 ft_type_bmp = 0; uint16 field_len = 0; uint32 flags = 0; soc_format_t fmt = INVALIDfmt; soc_field_info_t *field_info = NULL; _FP_FT_TRACKING_PARAM_QUAL_MAP_DECL; flags = _FP_FT_TRACKING_PARAM_F_NO_QUAL_MAPPED; ft_type_bmp = (BCMI_FT_TYPE_F_EFT | BCMI_FT_TYPE_F_AEFT); fmt = EFT_SESSION_DATA_BUSfmt; if (soc_format_field_valid(unit, fmt, NEXT_HOP_Bf)) { field_info = soc_format_fieldinfo_get(unit, fmt, NEXT_HOP_Bf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeNextHopB, 0, field_info->bp, field_info->len, ft_type_bmp); } } if (soc_format_field_valid(unit, fmt, NEXT_HOP_Af)) { field_info = soc_format_fieldinfo_get(unit, fmt, NEXT_HOP_Af); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeNextHopA, 0, field_info->bp, field_info->len, ft_type_bmp); } } if (soc_format_field_valid(unit, fmt, IP_PAYLOAD_LENGTHf)) { if (!SOC_IS_HURRICANE4(unit)) { field_info = soc_format_fieldinfo_get(unit, fmt, IP_PAYLOAD_LENGTHf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeIPPayloadLength, 0, field_info->bp, field_info->len, ft_type_bmp); } } } /* FWD_DOMAIN_ATTR */ /* FORWARDING_ZONE_TTL */ if (soc_format_field_valid(unit, fmt, PACKET_TOSf)) { field_info = soc_format_fieldinfo_get(unit, fmt, PACKET_TOSf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrPacketTos, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* FORWARDING_TYPE */ /* CONGESTION_EXPERIENCED */ if (soc_format_field_valid(unit, fmt, QOS_ATTRf)) { field_info = soc_format_fieldinfo_get(unit, fmt, QOS_ATTRf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeQosAttr, 0, field_info->bp, field_info->len, ft_type_bmp); } } if (soc_format_field_valid(unit, fmt, EGRESS_PORTf)) { field_info = soc_format_fieldinfo_get(unit, fmt, EGRESS_PORTf); if (field_info != NULL) { /* bits [15-8] in Egress port is reserved. So, ignore it */ field_len = field_info->len - 8; _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrPort, 0, field_info->bp, field_len, ft_type_bmp); } } /* DGPP */ /* Hr4 has MMU_COS_CEf and FB6 has MMU_COS_CMf */ if (soc_format_field_valid(unit, fmt, MMU_COS_CEf)) { field_info = soc_format_fieldinfo_get(unit, fmt, MMU_COS_CEf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUCos, 0, field_info->bp, field_info->len, ft_type_bmp); } } if (soc_format_field_valid(unit, fmt, MMU_COS_CMf)) { field_info = soc_format_fieldinfo_get(unit, fmt, MMU_COS_CMf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeMMUCos, 0, field_info->bp, field_info->len, ft_type_bmp); } } if (soc_format_field_valid(unit, fmt, OPAQUE_4_CLASS_IDf)) { field_info = soc_format_fieldinfo_get(unit, fmt, OPAQUE_4_CLASS_IDf); if (field_info != NULL) { _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrClassId, 0, field_info->bp, field_info->len, ft_type_bmp); } } /* Enable drop reason code tracking params based on feature * which in turn is set based on * OTP bit (DROP_ANALYSIS_DISABLE) */ if (soc_feature(unit, soc_feature_flowtracker_ver_2_drop_code)) { ft_type_bmp = (BCMI_FT_TYPE_F_EFT | BCMI_FT_TYPE_F_AEFT); _FP_FT_TRACKING_PARAM_QUAL_MAP_ADD(unit, map_db, flags, bcmFlowtrackerTrackingParamTypeEgrDropReasonGroupIdVector, 0, 240, 16, ft_type_bmp); } cleanup: return rv; } #endif /* BCM_FLOWTRACKER_V2_SUPPORT */ /* * Function: * bcmi_ft_group_tracking_params_per_ft_type_list * Purpose: * Show list of tracking params for given ft type * qualifiers. * Parameters: * unit - (IN) BCM device number. * map_db - (IN) param-qualifier map * ft_type_bmp- (IN) FT type * Returns: * BCM_E_XXX */ int bcmi_ft_group_tracking_params_per_ft_type_list( int unit, _field_ft_tracking_param_qual_map_db_t *map_db, uint16 ft_type_bmp) { bcmi_ft_type_t ft_type = bcmiFtTypeNone; bcm_flowtracker_tracking_param_type_t param; _field_ft_tracking_param_qual_map_t *pq_map = NULL; char *ft_type_str[] = BCMI_FT_TYPE_STRINGS; char *tracking_param_str[] = BCM_FT_TRACKING_PARAM_STRINGS; BCMI_FT_TYPE_F_UNIQUE_GET(ft_type_bmp, ft_type); LOG_CLI((BSL_META_U(unit, "\n\rFlowtracker Stage : %s\n\r"), ft_type_str[ft_type])); LOG_CLI((BSL_META_U(unit, "------------------------------------" "----------------\n\r"))); LOG_CLI((BSL_META_U(unit, " %40s | %s\n\r"), "Tracking Params", " Size")); LOG_CLI((BSL_META_U(unit, " %40s | %s\n\r"), "-------------------------------------", "-------")); for (param = bcmFlowtrackerTrackingParamTypeNone; param < bcmFlowtrackerTrackingParamTypeCount; param++) { pq_map = map_db->param_qual_map[param]; if (pq_map == NULL) { continue; } if (pq_map->db_ft_type_bmp & ft_type_bmp) { LOG_CLI((BSL_META_U(unit, " %40s | %4d\n\r"), tracking_param_str[param], pq_map->width/8)); } pq_map = NULL; } return BCM_E_NONE; } /* * Function: * bcmi_ft_group_tracking_params_per_ft_type_list * Purpose: * Show list of tracking params for given ft type * qualifiers. * Parameters: * unit - (IN) BCM device number. * req_ft_type_bmp- (IN) FT type * Returns: * BCM_E_XXX */ void bcmi_ft_group_tracking_params_list( int unit, uint16 req_ft_type_bmp) { int rv = BCM_E_NONE; int support = FALSE; _field_stage_t *stage_fc = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; /* Get FT Info */ rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); if (BCM_FAILURE(rv)) { return; } map_db = stage_fc->ft_info->param_qual_map_db; bcmi_esw_ft_type_support_check(unit, bcmiFtTypeIFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_IFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_IFT); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeMFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_MFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_MFT); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeEFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_EFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_EFT); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAIFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_AIFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_AIFT); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAMFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_AMFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_AMFT); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAEFT, &support); if ((support) && (req_ft_type_bmp & BCMI_FT_TYPE_F_AEFT)) { bcmi_ft_group_tracking_params_per_ft_type_list(unit, map_db, BCMI_FT_TYPE_F_AEFT); } return; } /* * Function: * _bcm_field_ft_udf_tracking_param_supported * Purpose: * Check if given tracking param need UDF for extraction. * qualifiers. * Parameters: * unit - (IN) BCM device number. * param - (IN) Tracking parameter * width - (OUT) Width if tracking param supported * Returns: * BCM_E_XXX */ int _bcm_field_ft_udf_tracking_param_supported( int unit, bcm_flowtracker_tracking_param_type_t param, uint16 *width) { int rv = BCM_E_NONE; _field_stage_t *stage_fc = NULL; _field_ft_info_t *ft_info = NULL; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; if (param >= _FIELD_FT_TRACKING_PARAM_MAX) { return FALSE; } rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); if (BCM_FAILURE(rv)) { return FALSE; } ft_info = stage_fc->ft_info; map_db = ft_info->param_qual_map_db; pq_map = map_db->param_qual_map[param]; if (pq_map == NULL) { return FALSE; } if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { *width = pq_map->width; return TRUE; } return FALSE; } /* * Function: * _bcm_field_ft_tracking_param_show * Purpose: * Show all tracking params alon with ft type supported * qualifiers. * Parameters: * unit - (IN) BCM device number. * Returns: * BCM_E_XXX */ int _bcm_field_ft_tracking_param_show(int unit) { int rv = BCM_E_NONE; int support = FALSE; _field_stage_t *stage_fc = NULL; _field_ft_info_t *ft_info = NULL; _field_ft_tracking_param_qual_map_t *pq_map = NULL; _field_ft_tracking_param_qual_map_db_t *map_db = NULL; bcm_flowtracker_tracking_param_type_t param; char *ft_type_str[] = BCMI_FT_TYPE_STRINGS; char *param_str[] = BCM_FT_TRACKING_PARAM_STRINGS; rv = _field_stage_control_get(unit, _BCM_FIELD_STAGE_FLOWTRACKER, &stage_fc); if (BCM_FAILURE(rv)) { return FALSE; } ft_info = stage_fc->ft_info; map_db = ft_info->param_qual_map_db; for (param = 0; param < bcmFlowtrackerTrackingParamTypeCount; param++) { pq_map = map_db->param_qual_map[param]; if (pq_map == NULL) { LOG_CLI((BSL_META_U(unit, " %40s | - Not Available -\n\r"), param_str[param])); continue; } LOG_CLI((BSL_META_U(unit, " %40s | %4d "), param_str[param], pq_map->width/8)); if (pq_map->flags & _FP_FT_TRACKING_PARAM_F_UDF_MAPPED) { LOG_CLI((BSL_META_U(unit, "UDF | "))); } else { LOG_CLI((BSL_META_U(unit, " | "))); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeIFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_IFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeIFT])); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeMFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_MFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeMFT])); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeEFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_EFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeEFT])); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAIFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_AIFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeAIFT])); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAMFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_AMFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeAMFT])); } bcmi_esw_ft_type_support_check(unit, bcmiFtTypeAEFT, &support); if ((support) && (pq_map->db_ft_type_bmp & BCMI_FT_TYPE_F_AEFT)) { LOG_CLI((BSL_META_U(unit, "%s,"), ft_type_str[bcmiFtTypeAEFT])); } LOG_CLI((BSL_META_U(unit, "\n\r"))); } return BCM_E_NONE; } #endif /* BCM_FLOWTRACKER_SUPPORT */
34.889239
134
0.629566
[ "object", "vector" ]
1762f470e7638db2e4483b4c0f6ba23d0eddb1bb
2,317
h
C
include/Core/Common/itkInPlaceImageFilterSerializer.h
finetjul/ParameterSerializer
d7e94d3ff9de9a8782db6997f8e1bc45626cfa3b
[ "Apache-2.0" ]
1
2018-01-14T21:05:08.000Z
2018-01-14T21:05:08.000Z
include/Core/Common/itkInPlaceImageFilterSerializer.h
thewtex/TubeTK-ParameterSerializer
67b34735c201d95cbfabf04f29bd120a12c63812
[ "Apache-2.0" ]
7
2016-08-22T19:23:41.000Z
2020-06-26T15:00:06.000Z
include/Core/Common/itkInPlaceImageFilterSerializer.h
thewtex/TubeTK-ParameterSerializer
67b34735c201d95cbfabf04f29bd120a12c63812
[ "Apache-2.0" ]
7
2016-08-22T19:21:14.000Z
2020-08-27T03:25:23.000Z
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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 __itkInPlaceImageFilterSerializer_h #define __itkInPlaceImageFilterSerializer_h #include "itkImageToImageFilterSerializer.h" namespace itk { /** \class InPlaceImageFilterSerializer * * \brief Parameter serializer for InPlaceImageFilter. * * \sa ParameterSerializer * */ template< class TInPlaceImageFilter > class InPlaceImageFilterSerializer: public ImageToImageFilterSerializer< typename TInPlaceImageFilter::Superclass > { public: /** Standard class typedefs. */ typedef InPlaceImageFilterSerializer Self; typedef ImageToImageFilterSerializer < typename TInPlaceImageFilter::Superclass > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; /** Method for creation through the object factory. */ itkNewMacro( Self ); /** Run-time type information (and related methods). */ itkTypeMacro( InPlaceImageFilterSerializer, ImageToImageFilterSerializer ); typedef TInPlaceImageFilter InPlaceImageFilterType; virtual void Serialize(); virtual void DeSerialize(); protected: InPlaceImageFilterSerializer(); virtual ~InPlaceImageFilterSerializer(); BoolValue * m_InPlace; private: InPlaceImageFilterSerializer( const Self & ); void operator=( const Self & ); // purposely not implemented }; } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkInPlaceImageFilterSerializer.hxx" #endif #endif
28.604938
81
0.698317
[ "object" ]
176354061b174f93e179672fe21e53f004cb3e0c
3,670
h
C
Projects/box_RayIntersect/box_rayIntersect_box.h
Neill3d/MoPlugs
84efea03e045f820f3dc132c1a60a779fc5e34fc
[ "BSD-3-Clause" ]
23
2017-10-20T07:01:18.000Z
2022-02-25T08:46:07.000Z
Projects/box_RayIntersect/box_rayIntersect_box.h
droidoid/MoPlugs
fce52e6469408e32e94af8ac8a303840bc956e53
[ "BSD-3-Clause" ]
1
2019-11-08T04:03:38.000Z
2019-11-10T10:16:00.000Z
Projects/box_RayIntersect/box_rayIntersect_box.h
droidoid/MoPlugs
fce52e6469408e32e94af8ac8a303840bc956e53
[ "BSD-3-Clause" ]
5
2017-12-03T20:43:27.000Z
2020-01-22T16:54:13.000Z
////////////////////////////////////////////////////////////////////////////////////////////////// // // file: box_rayIntersect_box.h // // Author Sergey Solokhin (Neill3d) // // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __BOX_RAY_INTERSECT_BOX_H__ #define __BOX_RAY_INTERSECT_BOX_H__ //--- SDK include #include <fbsdk/fbsdk.h> //--- Registration defines #define BOXRAYINTERSECT__CLASSNAME Box_RayIntersect #define BOXRAYINTERSECT__CLASSSTR "Box_RayIntersect" #define BOXSPHERECOORDS__CLASSNAME Box_SphereCoords #define BOXSPHERECOORDS__CLASSSTR "Box_SphereCoords" class RayIntersector { public: RayIntersector( FBVector3d pos, FBVector3d dir ) : mPos(pos) , mDir(dir) { mGeometry = nullptr; mMesh = nullptr; } bool intersectModel( FBModel *pModel ); struct IntersectionInfo { bool finded; int facet; // intersection face FBVector3d point; // ray intersection point double u; // facet u coord double v; // facet v coord } info; public: FBGeometry *mGeometry; FBMesh *mMesh; FBVector3d mPos; FBVector3d mDir; // calc intersection with a tri double calcIntersection( FBVector3d R0, FBVector3d R1, FBVector3d a, FBVector3d b, FBVector3d c ); // p - point on plane bool checkInside( FBVertex a, FBVertex b, FBVertex c, FBVector3d p ); int intersect_triangle( FBVector3d orig, FBVector3d dir, FBVector3d vert0, FBVector3d vert1, FBVector3d vert2, double &t, double &u, double &v ); }; /** Template for FBBox class. */ class Box_RayIntersect : public FBBox { //--- box declaration. FBBoxDeclare( Box_RayIntersect, FBBox ); public: //! creation function. virtual bool FBCreate(); //! destruction function. virtual void FBDestroy(); //! Overloaded FBBox real-time evaluation function. virtual bool AnimationNodeNotify(FBAnimationNode *pAnimationNode, FBEvaluateInfo *pEvaluateInfo); //! FBX Storage function virtual bool FbxStore( FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat ); //! FBX Retrieval function virtual bool FbxRetrieve( FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat ); private: FBAnimationNode *mNodeMesh; //!> input - mesh node FBAnimationNode *mRayStart; //!> input - ray start position FBAnimationNode *mRayDirection; //!> input - ray direction point FBAnimationNode *mIntersectPoint; //!> output - mesh intersection world point FBAnimationNode *mUVCoords[2]; //!> output - intersection u,v points }; class Box_SphereCoords : public FBBox { //--- box declaration. FBBoxDeclare( Box_SphereCoords, FBBox ); public: //! creation function. virtual bool FBCreate(); //! destruction function. virtual void FBDestroy(); //! Overloaded FBBox real-time evaluation function. virtual bool AnimationNodeNotify(FBAnimationNode *pAnimationNode, FBEvaluateInfo *pEvaluateInfo); //! FBX Storage function virtual bool FbxStore( FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat ); //! FBX Retrieval function virtual bool FbxRetrieve( FBFbxObject *pFbxObject, kFbxObjectStore pStoreWhat ); private: FBAnimationNode *mNodeMesh; //!> input - mesh node - use this mesh to untransform a ray and sphere coords FBAnimationNode *mRayStart; //!> input - ray start position FBAnimationNode *mRayDirection; //!> input - ray direction point FBAnimationNode *mSphereCoords[2]; //!> output - inclination, azimuth FBAnimationNode *mUVCoords[2]; //!> output - result u,v coords of a point }; #endif /* __BOX_RAY_INTERSECT_BOX_H__ */
27.80303
111
0.704087
[ "mesh" ]
176c049f1891f92fa6452b48b16c43b9b90f1f58
1,535
h
C
Sources/Core/Engine.h
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
1
2022-01-20T15:53:31.000Z
2022-01-20T15:53:31.000Z
Sources/Core/Engine.h
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
null
null
null
Sources/Core/Engine.h
carloshgsilva/VoxelEngine
5ba308d3573805437124f32d407306776c1d66d6
[ "MIT" ]
null
null
null
#pragma once #include "Core.h" #include "Window.h" #include "LayerStack.h" #include "Util/CallbackQueue.h" #include <iostream> class Engine { //std::vector<Ref<Layer>> layers //TODO: Events //Ref<EventDispatcher> eventDispatcher //TODO: Does The AssetManager need to be on the engine class? Nop it will be an EngineSystem CallbackQueue<void> _PostInitialize_Callbacks; CallbackQueue<Event&> _OnEvent_Callbacks; CallbackQueue<void> _OnBeforeUpdate_Callbacks; LayerStack _layerStack; float _lastTime; void StartEngine(); void Update(); public: void DispatchEvent(Event& E) { _OnEvent_Callbacks.ExecuteAll(E); if (E.Is<ViewportChangeEvent>()) { Update(); } for (auto& L : _layerStack) { L->OnEvent(E); } } static Engine& Get() { static Engine engine; return engine; } static void Create(); static void PushLayer(Ref<Layer> layer) { Get()._layerStack.PushLayer(layer); } static void PopLayer(){} static void PushOverlay(){} static void PopOverlay(){} static void Run(); static void OnBeforeUpdate(std::function<void()> _Func) { Get()._OnBeforeUpdate_Callbacks.AddCallback(_Func); } //Used by EngineSystems to Add An Callback that is called after all Systems have been initialized static void Bind_PostInitialize(std::function<void()> _Func) { Get()._PostInitialize_Callbacks.AddCallback(_Func); } //Used by EngineSystems to Handle Events static void Bind_OnEvent(std::function<void(Event&)> _Func) { Get()._OnEvent_Callbacks.AddCallback(_Func); } static double GetTime(); };
24.758065
117
0.735505
[ "vector" ]
177d3384ba0eaf6610ba7e833bf46c625e758907
10,588
h
C
Source/Dreemchest/Fx/Parameter.h
dmsovetov/Dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
11
2016-02-18T15:24:49.000Z
2021-01-30T18:26:04.000Z
Source/Dreemchest/Fx/Parameter.h
dmsovetov/dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
2
2016-05-23T22:48:35.000Z
2017-02-13T16:43:32.000Z
Source/Dreemchest/Fx/Parameter.h
dmsovetov/dreemchest
39255c88943abc69c7fa0710b7ca8486c08260e0
[ "MIT" ]
3
2016-08-19T13:26:59.000Z
2018-08-03T04:28:14.000Z
/************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Sovetov https://github.com/dmsovetov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **************************************************************************/ #ifndef __DC_Fx_Parameter_H__ #define __DC_Fx_Parameter_H__ #include "Fx.h" #define SampleParameter( idx, parameter, default ) ((parameter) ? (parameter)->sample( idx, scalar, default ) : (default)) #define SampleKoeficient( idx, parameter, default ) SampleParameter( idx, parameter, default * 100.0f ) * 0.01f DC_BEGIN_DREEMCHEST namespace Fx { //! Generic class used for declaring the parameter types. template<typename TValue> class Parameter { public: //! Parameter curve indices. enum CurveIndex { Lower = 0 //!< Parameter lower bound. , Upper //!< Parameter upper bounds. , TotalCurveIndices //!< The total number of curve indices. }; //! Compile time constant to define the randomization of particle lifetime parameters. enum { LifetimeRandomizationCount = 100 }; //! Alias the curve type. typedef Curve<TValue> CurveType; //! Constructs the Parameter instance. Parameter( void ); //! Returns true if the parameter is enabled. operator bool() const; //! Returns true if the parameter is enabled. bool isEnabled( void ) const; //! Enables or disables the parameter. void setEnabled( bool value ); //! Returns the parameter sampling mode. SamplingMode samplingMode( void ) const; //! Sets the parameter sampling mode. void setSamplingMode( SamplingMode value ); //! Sets the constant parameter value. void setConstant( const TValue& value ); //! Scales the parameter values. void scale( f32 value ); //! Returns the parameter curve by index. const CurveType& curve( CurveIndex index ) const; CurveType& curve( CurveIndex index ); //! Samples the parameter at specified time. TValue sample( s32 particleIndex, f32 scalar, const TValue& defaultValue = TValue() ) const; //! Generates the particle curves. void constructLifetimeCurves( void ); private: bool m_isEnabled; //!< The flag indicating that parameter is enabled. SamplingMode m_mode; //!< The parameter sampling mode. CurveType m_curves[TotalCurveIndices]; //!< Minimum and maximum curves. Array<CurveType> m_particleCurves; //!< Used for randomization of lifetime parameters. }; // ** Parameter::Parameter template<typename TValue> Parameter<TValue>::Parameter( void ) : m_isEnabled( false ), m_mode( SampleConstant ) { } // ** Parameter::operator bool template<typename TValue> Parameter<TValue>::operator bool() const { return m_isEnabled; } // ** Parameter::isEnabled template<typename TValue> bool Parameter<TValue>::isEnabled( void ) const { return m_isEnabled; } // ** Parameter::scale template<typename TValue> void Parameter<TValue>::scale( f32 value ) { for( s32 i = 0; i < TotalCurveIndices; i++ ) { for( s32 j = 0, n = m_curves[i].keyframeCount(); j < n; j++ ) { m_curves[i].keyframe( j ).m_value *= value; } } } // ** Parameter::setConstant template<typename TValue> void Parameter<TValue>::setConstant( const TValue& value ) { setSamplingMode( SampleConstant ); curve( Lower ).clear(); curve( Lower ).push( 0.0f, value ); } // ** Parameter::curve template<typename TValue> const typename Parameter<TValue>::CurveType& Parameter<TValue>::curve( CurveIndex index ) const { return m_curves[index]; } // ** Parameter::curve template<typename TValue> typename Parameter<TValue>::CurveType& Parameter<TValue>::curve( CurveIndex index ) { return m_curves[index]; } // ** Parameter::setEnabled template<typename TValue> void Parameter<TValue>::setEnabled( bool value ) { m_isEnabled = value; } // ** Parameter::samplingMode template<typename TValue> SamplingMode Parameter<TValue>::samplingMode( void ) const { return m_mode; } // ** Parameter::setSamplingMode template<typename TValue> void Parameter<TValue>::setSamplingMode( SamplingMode value ) { m_mode = value; } // ** Parameter::constructLifetimeCurves template<typename TValue> void Parameter<TValue>::constructLifetimeCurves( void ) { s32 size = m_curves[Lower].keyframeCount() > m_curves[Upper].keyframeCount() ? m_curves[Lower].keyframeCount() : m_curves[Upper].keyframeCount(); const CurveType& curve = m_curves[Lower].keyframeCount() > m_curves[Upper].keyframeCount() ? m_curves[Lower] : m_curves[Upper]; for( s32 i = 0; i < LifetimeRandomizationCount; i++ ) { CurveType random; for( s32 j = 0; j < size; j++ ) { const typename CurveType::Keyframe& keyframe = curve.keyframe( j ); TValue a, b; m_curves[Lower].sample( keyframe.m_time, a ); m_curves[Upper].sample( keyframe.m_time, b ); TValue result = randomValue( a, b ); random.push( keyframe.m_time, result ); } m_particleCurves.push_back( random ); } } // ** Parameter::sample template<typename TValue> TValue Parameter<TValue>::sample( s32 particleIndex, f32 scalar, const TValue& defaultValue ) const { NIMBLE_BREAK_IF( scalar < 0.0f || scalar > 1.0f, "scalar value is out of range" ); // Set result to a default value TValue result = defaultValue; switch( m_mode ) { case SampleConstant: { m_curves[Lower].value( 0, result ); } break; case SampleRandomBetweenConstants: { TValue a, b; m_curves[Lower].value( 0, a ); m_curves[Upper].value( 0, b ); result = randomValue( a, b ); } break; case SampleCurve: { m_curves[Lower].sample( scalar, result ); } break; case SampleRandomBetweenCurves: { // TValue a, b; // m_curves[Lower].sample( scalar, a ); // m_curves[Upper].sample( scalar, b ); // result = randomValue( a, b ); m_particleCurves[particleIndex].sample( scalar, result ); } break; default: NIMBLE_NOT_IMPLEMENTED } return result; } //! Float parameter type. class FloatParameter : public Parameter<f32> { public: //! Sets the scalar parameter data. void setData( const FloatArray& value, CurveIndex index ); //! Sets the curve parameter value. void setCurve( const FloatArray& data ); //! Sets the random between to constants parameter. void setRandomBetweenConstants( f32 min, f32 max ); //! Sets the random between curves parameter value. void setRandomBetweenCurves( const FloatArray& min, const FloatArray& max ); }; //! Vector parameter type. class Vec3Parameter : public Parameter<Vec3> { public: //! Sets the scalar parameter data. void setData( const FloatArray& value, CurveIndex index ); }; //! Rgb color parameter type. class RgbParameter : public Parameter<Rgb> { public: //! Sets the scalar parameter data. void setData( const FloatArray& value, CurveIndex index ); //! Sets the curve parameter value. void setCurve( const FloatArray& data ); //! Sets the random between curves parameter value. void setRandomBetweenCurves( const FloatArray& min, const FloatArray& max ); }; } // namespace Fx DC_END_DREEMCHEST #endif /* !__DC_Fx_Parameter_H__ */
36.891986
170
0.536929
[ "vector" ]
17853094e1aa498a7cb214a26c188be1e429917d
1,566
h
C
TMUIKit/TMUIComponents/ChainUI/Chainable/UIPageControl+Chainable.h
chengzongxin/TMUIKit
e22432708617ab5f8b0eb8849f1b3c9da1a4c99e
[ "MIT" ]
null
null
null
TMUIKit/TMUIComponents/ChainUI/Chainable/UIPageControl+Chainable.h
chengzongxin/TMUIKit
e22432708617ab5f8b0eb8849f1b3c9da1a4c99e
[ "MIT" ]
null
null
null
TMUIKit/TMUIComponents/ChainUI/Chainable/UIPageControl+Chainable.h
chengzongxin/TMUIKit
e22432708617ab5f8b0eb8849f1b3c9da1a4c99e
[ "MIT" ]
null
null
null
// // UIPageControl+Chainable.h // ChainUI // // Created by Joe.cheng on 2021/2/27. // #import <UIKit/UIKit.h> #import "CUIDefs.h" #define PageControl [UIPageControl new] NS_ASSUME_NONNULL_BEGIN @interface UIPageControl (Chainable) /** * numberOfPages * Usages: .pages(5) */ CUI_PC_PROP(Int) pages; /** * pageIndicatorTintColor * The tint color to be used for the page indicator. * color use Color() internally, so it can take any kind of arguments that Color() supported. * Usages: .color(@"red"), .color(@"#F00"), .color(@"255,0,0"), .color(colorObject), etc. * See UIColor+CUIChainable.h for more information. */ CUI_PC_PROP(Object) color; /** * currentPageIndicatorTintColor * The tint color to be used for the current page indicator. * highColor use Color() internally, so it can take any kind of arguments that Color() supported. * Usages: .highColor(@"red"), .highColor(@"#F00"), .highColor(@"255,0,0"), .highColor(colorObject), etc. * See UIColor+CUIChainable.h for more information. */ CUI_PC_PROP(Object) highColor; /** * Value did change callback. * Use UIControlEventValueChanged event internally. * It support two kind of arguments: 1) a callback block 2) a selector string * Usages: .onChange(^{}), .onChange(^(NSInteger currentPage){}), .onChange(^(NSInteger currentPage, id pageControl){}) .onChange(@"switchValueDidChange"), .onChange(@"switchValueDidChange:") */ CUI_PC_PROP(Callback) onChange; //hidesForSinglePage - (instancetype)hideForSingle; @end NS_ASSUME_NONNULL_END
25.672131
112
0.704342
[ "object" ]
178c400112199e9deacab3a1006f273b17d58b33
3,673
h
C
ardupilot/libraries/AP_Math/quaternion.h
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_Math/quaternion.h
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_Math/quaternion.h
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* 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 <http://www.gnu.org/licenses/>. */ // Copyright 2012 Andrew Tridgell, all rights reserved. // Refactored by Jonathan Challinger #ifndef QUATERNION_H #define QUATERNION_H #include <math.h> #if defined(MATH_CHECK_INDEXES) && (MATH_CHECK_INDEXES == 1) #include <assert.h> #endif class Quaternion { public: float q1, q2, q3, q4; // constructor creates a quaternion equivalent // to roll=0, pitch=0, yaw=0 Quaternion() { q1 = 1; q2 = q3 = q4 = 0; } // setting constructor Quaternion(const float _q1, const float _q2, const float _q3, const float _q4) : q1(_q1), q2(_q2), q3(_q3), q4(_q4) { } // function call operator void operator ()(const float _q1, const float _q2, const float _q3, const float _q4) { q1 = _q1; q2 = _q2; q3 = _q3; q4 = _q4; } // check if any elements are NAN bool is_nan(void) const { return isnan(q1) || isnan(q2) || isnan(q3) || isnan(q4); } // return the rotation matrix equivalent for this quaternion void rotation_matrix(Matrix3f &m) const; void from_rotation_matrix(const Matrix3f &m); // convert a vector from earth to body frame void earth_to_body(Vector3f &v) const; // create a quaternion from Euler angles void from_euler(float roll, float pitch, float yaw); void from_vector312(float roll ,float pitch, float yaw); void to_axis_angle(Vector3f &v); void from_axis_angle(Vector3f v); void from_axis_angle(const Vector3f &axis, float theta); void rotate(const Vector3f &v); void from_axis_angle_fast(Vector3f v); void from_axis_angle_fast(const Vector3f &axis, float theta); void rotate_fast(const Vector3f &v); // get euler roll angle float get_euler_roll() const; // get euler pitch angle float get_euler_pitch() const; // get euler yaw angle float get_euler_yaw() const; // create eulers from a quaternion void to_euler(float &roll, float &pitch, float &yaw) const; // create eulers from a quaternion Vector3f to_vector312(void) const; float length(void) const; void normalize(); // initialise the quaternion to no rotation void initialise() { q1 = 1.0f; q2 = q3 = q4 = 0.0f; } Quaternion inverse(void) const; // allow a quaternion to be used as an array, 0 indexed float & operator[](uint8_t i) { float *_v = &q1; #if defined(MATH_CHECK_INDEXES) && (MATH_CHECK_INDEXES == 1) assert(i < 4); #endif return _v[i]; } const float & operator[](uint8_t i) const { const float *_v = &q1; #if defined(MATH_CHECK_INDEXES) && (MATH_CHECK_INDEXES == 1) assert(i < 4); #endif return _v[i]; } Quaternion operator*(const Quaternion &v) const; Quaternion &operator*=(const Quaternion &v); Quaternion operator/(const Quaternion &v) const; }; #endif // QUATERNION_H
28.695313
95
0.653961
[ "vector" ]
1794a94d2df02c95f56f9ba0279cc4202bb21471
1,653
h
C
larcv/app/ThreadIO/BatchFillerMultiLabel.h
mmajewsk/larcv2
9ee74e42b293d547d3a8510fa2139b2d4ccf6b89
[ "MIT" ]
14
2017-10-19T15:08:29.000Z
2021-03-31T21:21:07.000Z
larcv/app/ThreadIO/BatchFillerMultiLabel.h
mmajewsk/larcv2
9ee74e42b293d547d3a8510fa2139b2d4ccf6b89
[ "MIT" ]
32
2017-10-25T22:54:06.000Z
2019-10-01T13:57:15.000Z
larcv/app/ThreadIO/BatchFillerMultiLabel.h
mmajewsk/larcv2
9ee74e42b293d547d3a8510fa2139b2d4ccf6b89
[ "MIT" ]
16
2017-12-07T12:04:40.000Z
2021-11-15T00:53:31.000Z
/** * \file BatchFillerMultiLabel.h * * \ingroup ThreadIO * * \brief Class def header for a class BatchFillerMultiLabel * * @author kazuhiro */ /** \addtogroup ThreadIO @{*/ #ifndef __BATCHFILLERMULTILABEL_H__ #define __BATCHFILLERMULTILABEL_H__ #include "larcv/core/Processor/ProcessFactory.h" #include "BatchFillerTemplate.h" namespace larcv { /** \class ProcessBase User defined class BatchFillerMultiLabel ... these comments are used to generate doxygen documentation! */ class BatchFillerMultiLabel : public BatchFillerTemplate<float> { public: /// Default constructor BatchFillerMultiLabel(const std::string name="BatchFillerMultiLabel"); /// Default destructor ~BatchFillerMultiLabel(){} void configure(const PSet&); void initialize(); bool process(IOManager& mgr); void _batch_begin_(); void _batch_end_(); void finalize(); private: std::string _part_producer; std::vector<float> _entry_data; size_t _num_class; std::vector<int> _pdg_list; }; /** \class larcv::BatchFillerMultiLabelFactory \brief A concrete factory class for larcv::BatchFillerMultiLabel */ class BatchFillerMultiLabelProcessFactory : public ProcessFactoryBase { public: /// ctor BatchFillerMultiLabelProcessFactory() { ProcessFactory::get().add_factory("BatchFillerMultiLabel",this); } /// dtor ~BatchFillerMultiLabelProcessFactory() {} /// creation method ProcessBase* create(const std::string instance_name) { return new BatchFillerMultiLabel(instance_name); } }; } #endif /** @} */ // end of doxygen group
22.04
110
0.702964
[ "vector" ]
1798543597e605a52d0c802c6c9489f2615faa36
2,192
h
C
src/mongo/db/auth/security_file.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/auth/security_file.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/auth/security_file.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include <string> #include <vector> namespace mongo { template <class T> class StatusWith; /** * This method takes in a filename and returns the contents as a vector of strings. * * The contents of the file are interpreted as a YAML file and may either contain a scalar (string) * value or a sequence of scalar values. Each value may only contain valid base-64 characters. * * Whitespace within each key will be stripped from the final keys (e.g. "key 1" = "key1"). * * This will return an error if the file was empty or contained invalid characters. */ StatusWith<std::vector<std::string>> readSecurityFile(const std::string& filename); } // namespace mongo
42.153846
99
0.726734
[ "vector" ]
1798cce4234d75126e6446c07dfd59133bfd60ce
14,387
c
C
termsrv/drivers/rdp/rdpperf/utilsub/procutil.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
termsrv/drivers/rdp/rdpperf/utilsub/procutil.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
termsrv/drivers/rdp/rdpperf/utilsub/procutil.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************************** * PROCUTIL.C * * Various useful utilities for dealing with processes under CITRIX NT * Multi-user that are useful across a range of utilities and apps. * * Copyright Citrix Systems Inc. 1994 * Copyright (C) 1997-1999 Microsoft Corp. * * Author: John Richardson *******************************************************************************/ #include <nt.h> #include <ntrtl.h> #include <nturtl.h> #include <windows.h> #include <ntddkbd.h> #include <ntddmou.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <process.h> #include <string.h> #include <malloc.h> #include <winstaw.h> #include <utilsub.h> /* * Local function prototypes. */ VOID LookupSidUser( PSID pSid, PWCHAR pUserName, PULONG pcbUserName ); /* * RefreshProcessObjectCaches() * * Refresh (invalidate) any caches that may be used by process object * utilities. * * This is currently a place holder, but is here so that utilities can call * it, thus being isolated from any future decisions to add caching. */ VOID WINAPI RefreshProcessObjectCaches() { RefreshUserSidCrcCache(); } /****************************************************************************** * * ProcessObjectMatch * * General Name match function against a process. * * The CITRIX admin utilities can take a user name, winstation name, * a winstation id, or process id as an argument to a command that targets * a process for some action (query status, kill, etc.) * * This function does general compares of the supplied name to see if it * applies to the given process because the name represents the NT user * account, a winstations system name, the winstations unique id, or the * processes unique id. It replaces some of the function in MumProc() * on the CITRIX OS/2 product. * * The various information about a process is supplied by the caller. Because * of the way processes are enumerated from the NT system, it is easier * and faster for the caller to supply this information than for the routine * to retrieve it itself. This could be folded into a general EnumerateProcess() * if needed. Currently this routine serves the purpose of having one unified * way of handling process objects across all utilities. * * * Matching: * * An integer number is assumed to be an NT process ID unless NumberIsLogonId * is set, which then says to treat it as a LogonId. * * A name starting with a character is tested first as a winstation name, then * as a user name, finally as a program image name. A user or group name * could stand alone, or be preceded by a '\' to be [somewhat] compatible * with the OS/2 product. * * Parameters: * * Pid (input) * Windows NT unique process identifier * LogonId (input) * CITRIX Logon ID the process is executing on. * NumberIsLogonId (input) * Treat a number in pMatchName as a LogonId not an PID number. * pMatchName (input) * Name for match testing * pWinStationName (input) * Name of WinStation for process. * pUserName (input) * Name of User for process. * pImageName (input) * Image name of executing program for process. * *****************************************************************************/ BOOLEAN WINAPI ProcessObjectMatch( ULONG Pid, ULONG LogonId, int NumberIsLogonId, PWCHAR pMatchName, PWCHAR pWinStationName, PWCHAR pUserName, PWCHAR pImageName ) { ULONG tmp; /* * Check for wild card */ if( pMatchName[0] == L'*' ) return( TRUE ); /* * If someone puts a '\' in front of pMatchName, strip it off */ if( pMatchName[0] == L'\\' ) pMatchName++; /* * First, if the match name is a number, check for == to process ID or * LogonId. */ if( iswdigit( pMatchName[0] ) ) { tmp = wcstol( pMatchName, NULL, 10 ); if( NumberIsLogonId && (tmp == LogonId) ) return( TRUE ); else if( tmp == Pid ) return( TRUE ); else return( FALSE ); } /* * Then, check the match name against the WinStation Name of the process. */ if ( !_wcsicmp( pWinStationName, pMatchName ) ) { return( TRUE ); } /* * Then, check the match name against the UserName of the process. */ if( !_wcsicmp( pUserName, pMatchName ) ) { return( TRUE ); } /* * Finally, check the match name against the image name of the process. */ if( !_wcsicmp( pImageName, pMatchName ) ) { return(TRUE); } return( FALSE ); } /* * This is the cache maintained by the GetUserNameFromSid function * * It is thread safe through the use of ULock. */ typedef struct TAGUSERSIDLIST { struct TAGUSERSIDLIST *Next; USHORT SidCrc; WCHAR UserName[USERNAME_LENGTH]; } USERSIDLIST, *PUSERSIDLIST; static PUSERSIDLIST pUList = NULL; static RTL_CRITICAL_SECTION ULock; static BOOLEAN ULockInited = FALSE; /*************************************************************************** * * InitULock * * Since we do not require the user to call an initialize function, * we must initialize our critical section in a thread safe manner. * * The problem is, a critical section is needed to guard against multiple * threads trying to init the critical section at the same time. * * The solution that Nt uses, in which RtlInitializeCriticalSection itself * uses, is to wait on a kernel supported process wide Mutant before proceding. * This Mutant almost works by itself, but RtlInitializeCriticalSection does * not wait on it until after trashing the semaphore count. So we wait on * it ourselves, since it can be acquired recursively. * ***************************************************************************/ NTSTATUS InitULock() { NTSTATUS status = STATUS_SUCCESS; RtlEnterCriticalSection((PRTL_CRITICAL_SECTION)NtCurrentPeb()->LoaderLock); /* * Make sure another thread did not beat us here */ if( ULockInited == FALSE ){ status = RtlInitializeCriticalSection( &ULock ); if (status == STATUS_SUCCESS) { ULockInited = TRUE; } } RtlLeaveCriticalSection((PRTL_CRITICAL_SECTION)NtCurrentPeb()->LoaderLock); return status; } /*************************************************************************** * * RefreshUserSidCrcCache * * Invalidate the User/SidCrc cache so that the newest information * will be fetched from the system. * ***************************************************************************/ VOID WINAPI RefreshUserSidCrcCache( ) { NTSTATUS status = STATUS_SUCCESS; PUSERSIDLIST pEntry, pNext; if( pUList == NULL ) return; /* * Make sure critical section has been inited */ if( !ULockInited ) { status = InitULock(); } if (status == STATUS_SUCCESS) { RtlEnterCriticalSection( &ULock ); pEntry = pUList; while( pEntry ) { pNext = pEntry->Next; free( pEntry ); pEntry = pNext; } pUList = NULL; RtlLeaveCriticalSection( &ULock ); } } /****************************************************************************** * * GetUserNameFromSid * * Attempts to retrieve the user (login) name of the process by first looking * in our User/SidCrc cache table, then (if no match) looking up the SID in * the SAM database and adding the new entry to the User/SidCrc table. * * Input * * IN pUserSid Sid pointer * * OUT NameBuf WCHAR pointer to buffer for name * * IN/OUT pBufSize PULONG NameBuf size * * Will always return a user name, which will be "(unknown)" if the SID is * invalid or can't determine the user/SID relationship for any other reason. * *****************************************************************************/ VOID WINAPI GetUserNameFromSid( PSID pUserSid, PWCHAR pBuffer, PULONG pcbBuffer ) { NTSTATUS status = STATUS_SUCCESS; USHORT SidCrc = 0; PUSERSIDLIST pEntry; /* * Make sure critical section has been inited */ if( !ULockInited ) { status = InitULock(); } /* * Determine SID length in bytes and calculate a 16-bit CRC for it, * to facilitate quick matching. */ if ( pUserSid ) SidCrc = CalculateCrc16( (PBYTE)pUserSid, (USHORT)GetLengthSid(pUserSid) ); /* * First: Before performing the expensive LookupAccountSid() function, * see if we've encountered this SID already, and match the user name * if so. */ if ( status == STATUS_SUCCESS && pUList ) { RtlEnterCriticalSection( &ULock ); pEntry = pUList; while( pEntry ) { if ( SidCrc == pEntry->SidCrc ) { wcsncpy( pBuffer, pEntry->UserName, (*pcbBuffer)-1 ); pBuffer[(*pcbBuffer)-1] = 0; *pcbBuffer = wcslen(pBuffer); RtlLeaveCriticalSection( &ULock ); return; } pEntry = pEntry->Next; } RtlLeaveCriticalSection( &ULock ); } /* * Last resort: Determine the user name associated with the SID using * the LookupAccountSid() API, embedded in our local function * LookupSidUser(). */ LookupSidUser( pUserSid, pBuffer, pcbBuffer ); /* * Add this new User/Sid relationship in our User/Sid cache list. */ if (status == STATUS_SUCCESS) { RtlEnterCriticalSection( &ULock ); if ( (pEntry = (PUSERSIDLIST)malloc(sizeof(USERSIDLIST))) ) { pEntry->SidCrc = SidCrc; wcsncpy( pEntry->UserName, pBuffer, USERNAME_LENGTH - 1 ); pEntry->UserName[USERNAME_LENGTH-1] = 0; pEntry->Next = pUList; pUList = pEntry; } RtlLeaveCriticalSection( &ULock ); } } /****************************************************************************** * LookupSidUser * * Fetch the user name associated with the specified SID. * * ENTRY: * pSid (input) * Points to SID to match to user name. * pUserName (output) * Points to buffer to place the user name into. * pcbUserName (input/output) * Specifies the size in bytes of the user name buffer. The returned * user name will be truncated to fit this buffer (including NUL * terminator) if necessary and this variable set to the number of * characters copied to pUserName. * * EXIT: * * LookupSidUser() will always return a user name. If the specified * SID fails to match to a user name, then the user name "(unknown)" will * be returned. * *****************************************************************************/ VOID LookupSidUser( PSID pSid, PWCHAR pUserName, PULONG pcbUserName ) { WCHAR DomainBuffer[DOMAIN_LENGTH], UserBuffer[USERNAME_LENGTH]; DWORD cbDomainBuffer=sizeof(DomainBuffer), cbUserBuffer=sizeof(UserBuffer), Error; PWCHAR pDomainBuffer = NULL, pUserBuffer = NULL; SID_NAME_USE SidNameUse; PWCHAR pUnknown = L"(unknown)"; /* * Fetch user name from SID: try user lookup with a reasonable Domain and * Sid buffer size first, before resorting to alloc. */ if ( !LookupAccountSid( NULL, pSid, UserBuffer, &cbUserBuffer, DomainBuffer, &cbDomainBuffer, &SidNameUse ) ) { if ( ((Error = GetLastError()) == ERROR_INSUFFICIENT_BUFFER) ) { if ( cbDomainBuffer > sizeof(DomainBuffer) ) { if ( !(pDomainBuffer = (PWCHAR)malloc( cbDomainBuffer * sizeof(WCHAR))) ) { Error = ERROR_NOT_ENOUGH_MEMORY; goto BadDomainAlloc; } } if ( cbUserBuffer > sizeof(UserBuffer) ) { if ( !(pUserBuffer = (PWCHAR)malloc( cbUserBuffer * sizeof(WCHAR))) ) { Error = ERROR_NOT_ENOUGH_MEMORY; goto BadUserAlloc; } } if ( !LookupAccountSid( NULL, pSid, pUserBuffer ? pUserBuffer : UserBuffer, &cbUserBuffer, pDomainBuffer ? pDomainBuffer : DomainBuffer, &cbDomainBuffer, &SidNameUse ) ) { Error = GetLastError(); goto BadLookup; } } else { goto BadLookup; } } /* * Copy the user name into the specified buffer, truncating if necessary. */ wcsncpy( pUserName, pUserBuffer ? pUserBuffer : UserBuffer, (*pcbUserName)-1 ); pUserName[(*pcbUserName)-1] = 0; *pcbUserName = wcslen(pUserName); /* * Free our allocs (if any) and return. */ if ( pDomainBuffer ) free(pDomainBuffer); if ( pUserBuffer ) free(pUserBuffer); return; /*-------------------------------------- * Error clean-up and return... */ BadLookup: BadUserAlloc: BadDomainAlloc: if ( pDomainBuffer ) free(pDomainBuffer); if ( pUserBuffer ) free(pUserBuffer); wcsncpy( pUserName, pUnknown, (*pcbUserName)-1 ); pUserName[(*pcbUserName)-1] = 0; *pcbUserName = wcslen(pUserName); return; }
29.848548
81
0.544033
[ "object" ]
17a05ce7102724dcc50765c704235629eb691bae
3,821
h
C
source/PEST++/src/libs/Eigen/bench/spbench/spbenchstyle.h
usgs/neversink_workflow
acd61435b8553e38d4a903c8cd7a3afc612446f9
[ "CC0-1.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
SCA/eigen_332/bench/spbench/spbenchstyle.h
JooseRajamaeki/TVCG18
ddc73f422c267b1c38ede3ba20046efff46a6d74
[ "MIT" ]
113
2015-07-28T20:31:48.000Z
2022-03-01T15:29:20.000Z
SCA/eigen_332/bench/spbench/spbenchstyle.h
JooseRajamaeki/TVCG18
ddc73f422c267b1c38ede3ba20046efff46a6d74
[ "MIT" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr> // // 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 SPBENCHSTYLE_H #define SPBENCHSTYLE_H void printBenchStyle(std::ofstream& out) { out << "<xsl:stylesheet id='stylesheet' version='1.0' \ xmlns:xsl='http://www.w3.org/1999/XSL/Transform' >\n \ <xsl:template match='xsl:stylesheet' />\n \ <xsl:template match='/'> <!-- Root of the document -->\n \ <html>\n \ <head> \n \ <style type='text/css'> \n \ td { white-space: nowrap;}\n \ </style>\n \ </head>\n \ <body>"; out<<"<table border='1' width='100%' height='100%'>\n \ <TR> <!-- Write the table header -->\n \ <TH>Matrix</TH> <TH>N</TH> <TH> NNZ</TH> <TH> Sym</TH> <TH> SPD</TH> <TH> </TH>\n \ <xsl:for-each select='BENCH/AVAILSOLVER/SOLVER'>\n \ <xsl:sort select='@ID' data-type='number'/>\n \ <TH>\n \ <xsl:value-of select='TYPE' />\n \ <xsl:text></xsl:text>\n \ <xsl:value-of select='PACKAGE' />\n \ <xsl:text></xsl:text>\n \ </TH>\n \ </xsl:for-each>\n \ </TR>"; out<<" <xsl:for-each select='BENCH/LINEARSYSTEM'>\n \ <TR> <!-- print statistics for one linear system-->\n \ <TH rowspan='4'> <xsl:value-of select='MATRIX/NAME' /> </TH>\n \ <TD rowspan='4'> <xsl:value-of select='MATRIX/SIZE' /> </TD>\n \ <TD rowspan='4'> <xsl:value-of select='MATRIX/ENTRIES' /> </TD>\n \ <TD rowspan='4'> <xsl:value-of select='MATRIX/SYMMETRY' /> </TD>\n \ <TD rowspan='4'> <xsl:value-of select='MATRIX/POSDEF' /> </TD>\n \ <TH> Compute Time </TH>\n \ <xsl:for-each select='SOLVER_STAT'>\n \ <xsl:sort select='@ID' data-type='number'/>\n \ <TD> <xsl:value-of select='TIME/COMPUTE' /> </TD>\n \ </xsl:for-each>\n \ </TR>"; out<<" <TR>\n \ <TH> Solve Time </TH>\n \ <xsl:for-each select='SOLVER_STAT'>\n \ <xsl:sort select='@ID' data-type='number'/>\n \ <TD> <xsl:value-of select='TIME/SOLVE' /> </TD>\n \ </xsl:for-each>\n \ </TR>\n \ <TR>\n \ <TH> Total Time </TH>\n \ <xsl:for-each select='SOLVER_STAT'>\n \ <xsl:sort select='@ID' data-type='number'/>\n \ <xsl:choose>\n \ <xsl:when test='@ID=../BEST_SOLVER/@ID'>\n \ <TD style='background-color:red'> <xsl:value-of select='TIME/TOTAL' /> </TD>\n \ </xsl:when>\n \ <xsl:otherwise>\n \ <TD> <xsl:value-of select='TIME/TOTAL' /></TD>\n \ </xsl:otherwise>\n \ </xsl:choose>\n \ </xsl:for-each>\n \ </TR>"; out<<" <TR>\n \ <TH> Error </TH>\n \ <xsl:for-each select='SOLVER_STAT'>\n \ <xsl:sort select='@ID' data-type='number'/>\n \ <TD> <xsl:value-of select='ERROR' />\n \ <xsl:if test='ITER'>\n \ <xsl:text>(</xsl:text>\n \ <xsl:value-of select='ITER' />\n \ <xsl:text>)</xsl:text>\n \ </xsl:if> </TD>\n \ </xsl:for-each>\n \ </TR>\n \ </xsl:for-each>\n \ </table>\n \ </body>\n \ </html>\n \ </xsl:template>\n \ </xsl:stylesheet>\n\n"; } #endif
40.648936
99
0.474483
[ "transform" ]
17a15a2a45b97bd74d998aad57becd384afa5118
8,969
h
C
include/ossim/projection/ossimFcsiModel.h
DigitalGlobe/ossim
a03729866f15bcf3bf210e14d395c683321b12bc
[ "MIT" ]
1
2018-03-04T10:45:56.000Z
2018-03-04T10:45:56.000Z
include/ossim/projection/ossimFcsiModel.h
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
null
null
null
include/ossim/projection/ossimFcsiModel.h
IvanLJF/ossim
2e0143f682b9884a09ff2598ef8737f29e44fbdf
[ "MIT" ]
1
2018-10-11T11:36:16.000Z
2018-10-11T11:36:16.000Z
//******************************************************************* // // License: See top level LICENSE.txt file. // // DESCRIPTION: Contains sensor model class declaration for "Frame Camera // Scanned Image" (FCSI, pronounced "foxy"). // // This model represents image data that was scanned from film exposed by a // conventional aerial frame camera. The data members defined in this class // represent the fundamental quantities needed for the transformation. // Typically, a different set of parameters will be provided in the metadata. // An interface (support data) class will need to be implemented to convert // a particular system's format to the quantities needed by this model. // // Coordinate systems in use are described here: // // Pixel -- line/sample in the digital image. The origin of this system is // the upper left corner of the image, and represents a LEFT- // HANDED coordinate system with Y (line) positive down and X // (sample) positive to the right. // // Film -- x, y related to pixel space by affine transform (which includes // mirror reflection due to left-handed system above) represented // by thePrincipalPoint and the theScanXformMatrix. The latter // contains scale, skew, and rotation/reflection. The film // coordinates are adjusted for radial and decentering distortion. // // Camera/ -- 3D system containing film plane and optical (Z) axis. Given the // Platform focal length (Z) and the film point (X,Y), a 3D ray direction // is established in this space. This space is also termed "LSR" // in the code. If there is a rotation between the film/optical // axes and the platform (interior orientation), then that // transformation must be included as part of the LSR-to-ECF // rotation by the metadata reader object. // // ECF -- Universal earth frame of reference. The imaging ray direction // is transformed from Camera space to ECF by theAdjLsrToEcfRot. // // There are two rotations to go from Camera to ECF. First is the initial // camera orientation as derived from the metadata, combining the interior // orientation (relation between camera and platform) and the exterior // orientation dependent on the platform attitude w.r.t. the ECF system. // The second rotation is a differential rotation due to the attitude // adjustable params. These are arbitrarily taken as rotations about the ECF // XYZ axes, not the platform attitude axes of roll/pitch/yaw. The // combined rotation is stored in theAdjLsrToEcfRot, which is precomputed // in updateModel() once with each adjustment. // // When the time comes to incorporate least-squares parameter adjustment, care // must be taken to propagate the a priori sigmas for position and attitude // (including both internal and external orientation angles) into the ECF // coordinates. This also applies to the affine transform parameters used in // transforming pixels to film coordinates. The propagated uncertainties can // then be used to assign the adjustable parameter sigmas array (and // covariance when we get to that...) // // SOFTWARE HISTORY: // 16JAN2003 Oscar Kramer, ImageLinks // Initial coding // //***************************************************************************** // $Id: ossimFcsiModel.h 15766 2009-10-20 12:37:09Z gpotts $ #ifndef ossimFcsiModel_HEADER #define ossimFcsiModel_HEADER #include <iostream> using namespace std; #include <ossim/projection/ossimSensorModel.h> #include <ossim/base/ossimFilename.h> #include <ossim/base/ossimDpt.h> #include <ossim/base/ossimEcefPoint.h> #include <ossim/base/ossimMatrix3x3.h> #include <ossim/projection/ossimRadialDecentLensDistortion.h> //****************************************************************************** // // CLASS: ossimFcsiModel // //****************************************************************************** class OSSIM_DLL ossimFcsiModel : public ossimSensorModel { public: /*! * CONSTRUCTORS: */ ossimFcsiModel(); ossimFcsiModel(const ossimFilename& init_file); ossimFcsiModel(const ossimKeywordlist& geom_kwl); ossimFcsiModel(const ossimFcsiModel& rhs); enum AdjustParamIndex { X_POS = 0, Y_POS, Z_POS, X_ROT, Y_ROT, Z_ROT, FOCAL_LEN, SCAN_SKEW, NUM_ADJUSTABLE_PARAMS // not an index }; /*! * Returns pointer to a new instance, copy of this. */ virtual ossimObject* dup() const { return new ossimFcsiModel(*this); } /*! * Extends base-class implementation. Dumps contents of object to ostream. */ virtual std::ostream& print(std::ostream& out) const; /*! * Fulfills ossimObject base-class pure virtuals. Loads and saves geometry * KWL files. Returns true if successful. */ virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0) const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); /*! * Writes a template of geom keywords processed by loadState and saveState * to output stream. */ static void writeGeomTemplate(ostream& os); /*! * Overrides base class pure virtual. */ virtual void lineSampleHeightToWorld(const ossimDpt& image_point, const double& heightEllipsoid, ossimGpt& worldPoint) const; /*! * Given an image point, returns a ray originating at some arbitrarily high * point (ideally at the sensor position) and pointing towards the target. */ virtual void imagingRay(const ossimDpt& image_point, ossimEcefRay& image_ray) const; /*! * Rigorous inverse transform implented, overrides base-class' iterative * solution. */ virtual void worldToLineSample(const ossimGpt& world_point, ossimDpt& image_point) const; /*! * Following a change to the adjustable parameter set, this virtual * is called to permit instances to compute derived quantities after * parameter change. */ virtual void updateModel(); /*! * Global keywords for use by this model: */ static const char* PRINCIPAL_POINT_X_KW; static const char* PRINCIPAL_POINT_Y_KW; static const char* SCAN_SCALE_MATRIX_00_KW; static const char* SCAN_SCALE_MATRIX_01_KW; static const char* SCAN_SCALE_MATRIX_10_KW; static const char* SCAN_SCALE_MATRIX_11_KW; static const char* SCAN_SKEW_ANGLE_KW; static const char* SCAN_ROTATION_ANGLE_KW; static const char* FOCAL_LENGTH_KW; static const char* PLATFORM_POSITION_X_KW; static const char* PLATFORM_POSITION_Y_KW; static const char* PLATFORM_POSITION_Z_KW; static const char* CAMERA_ORIENTATION_MATRIX_ELEM_KW; /*! * ossimOptimizableProjection */ inline virtual bool useForward()const {return true;} //!ground to image faster (you don't need DEM) protected: virtual ~ossimFcsiModel() { delete theOpticalDistortion; } /*! * Assigns initial default values to adjustable parameters and related * members. */ void initAdjustableParameters(); //*** // Affine transform variables for scanned image to film coordinate // transformation, in order of application: //*** ossimDpt thePrincipalPoint; // principal point location in pixels double theScanScaleMatrix[4];// converts pixel to film X, Y mm double theScanSkew; // degrees double theScanRotation; // degrees left rotation of scanned image //*** // Transform variables for film coordinates to platform LSR (interior // orientation): //*** double theFocalLen; // millimeters ossimRadialDecentLensDistortion* theOpticalDistortion; //*** // Transform variables for platform LSR to ECF coordinates (interior/exterior // orientation and offset): //*** ossimEcefPoint thePlatformPos; NEWMAT::Matrix theLsrToEcfRot; //*** // Un-normalized adjustable parameters: //*** ossimEcefVector theEcfOffset; // meters double theXrotCorr; // degrees double theYrotCorr; // degrees double theZrotCorr; // degrees double theFocalOffset; // millimeters double theScanSkewCorr; // degrees //*** // Quantities derived from adjustables and assigned in updateModel(): //*** ossimEcefPoint theAdjPlatformPos; double theAdjFocalLen; NEWMAT::Matrix theAdjLsrToEcfRot; NEWMAT::Matrix theAdjEcfToLsrRot; double theScanXformMatrix[4]; double theInvScanXformMatrix[4]; TYPE_DATA }; #endif
37.527197
102
0.653362
[ "geometry", "object", "model", "transform", "3d" ]
17aa807a7a5d6c85e7366f740686bf7ac88d49f7
1,929
h
C
sdk-remote/src/swig/java/src/urbi_UObject.h
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
16
2016-05-10T05:50:58.000Z
2021-10-05T22:16:13.000Z
sdk-remote/src/swig/java/src/urbi_UObject.h
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
7
2016-09-05T10:08:33.000Z
2019-02-13T10:51:07.000Z
sdk-remote/src/swig/java/src/urbi_UObject.h
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
15
2015-01-28T20:27:02.000Z
2021-09-28T19:26:08.000Z
/* * Copyright (C) 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> #include "api.h" /* Header for class liburbi_main_UObjectJava */ #ifndef _Included_urbi_UObject #define _Included_urbi_UObject #ifdef __cplusplus extern "C" { #endif /* * Class: urbi_UObject * Method: registerNotifyOnRequest * Signature: (JLjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V */ URBIJAVA_API JNIEXPORT void JNICALL Java_urbi_UObject_registerNotifyOnRequest (JNIEnv *, jobject, jlong, jstring, jboolean, jstring, jstring, jstring, jstring, jint, jobjectArray); /* * Class: urbi_UObject * Method: registerNotifyChange * Signature: (JLjava/lang/String;ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V */ URBIJAVA_API JNIEXPORT void JNICALL Java_urbi_UObject_registerNotifyChange (JNIEnv *, jobject, jlong, jstring, jboolean, jstring, jstring, jstring, jstring, jint, jobjectArray); /* * Class: urbi_UObject * Method: registerFunction * Signature: (Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V */ URBIJAVA_API JNIEXPORT void JNICALL Java_urbi_UObject_registerFunction (JNIEnv *, jobject, jobject, jstring, jstring, jstring, jstring, jint, jobjectArray); /* * Class: urbi_UObject * Method: registerTimerFunction * Signature: (Ljava/lang/Object;Ljava/lang/String;DLjava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V */ URBIJAVA_API JNIEXPORT jstring JNICALL Java_urbi_UObject_registerTimerFunction (JNIEnv *, jobject, jobject, jstring, jdouble, jstring, jstring, jstring, jint); #ifdef __cplusplus } #endif #endif
33.258621
109
0.758942
[ "object" ]
c0a19dc4859c23b96d1cec5a96c69df166012a0a
1,058
h
C
source/SX_VMF.h
xNWP/SourceX-R18-
4db904731ce7cdcdfdf5d1394f820a6e4e44e501
[ "MIT" ]
2
2018-11-14T09:47:13.000Z
2021-09-06T16:35:12.000Z
source/SX_VMF.h
xNWP/SourceX-R18-
4db904731ce7cdcdfdf5d1394f820a6e4e44e501
[ "MIT" ]
null
null
null
source/SX_VMF.h
xNWP/SourceX-R18-
4db904731ce7cdcdfdf5d1394f820a6e4e44e501
[ "MIT" ]
1
2019-07-18T01:15:14.000Z
2019-07-18T01:15:14.000Z
// Copyright (c) 2018 Brett Anthony. All rights reserved. // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. // Defines various functions to aid in parsing vmf files. #ifndef SX_VMF_H #define SX_VMF_H #include "c4d.h" #include "SX_Solid.h" #include "SX_Plane.h" #include "c4d_symbols.h" #include <vector> #include <map> std::vector<String>& ParseProperties(const String&); std::vector<Vector>& ParseVector3(const String&); Vector& ParseVector(const String&, Int32, Int32); std::vector<Vector>& ParseVectorArray(const String&); std::vector<Float32>& ParseFloatArray(const String&); std::vector<String>& ParseLines(const String&); void ClassBounds(std::vector<String>&, String, int&, int&); void GetVertices(SX_Solid&, const Int32&); Bool VectorInList(const Vector&, const std::vector<Vector>&); void OrderByAngle(SX_Plane&); Float32 Distance(const Vector&, const Vector&); std::vector<std::vector<Int32>>& FindLikePoints(const std::vector<Int32>&, const std::vector<Vector>&); #endif
34.129032
103
0.744802
[ "vector" ]
c0ab69a307929cab8093a933602f66bb0ca1314a
10,773
c
C
src/plugins/simulator/physics_engines/dynamics2d/chipmunk-physics/src/cpBody.c
daneshtarapore/argos3-asv
208e23bfab382b71dbbb5de1ec3d749e8ae194d3
[ "MIT" ]
2
2017-09-06T11:33:18.000Z
2017-09-06T11:33:22.000Z
src/plugins/simulator/physics_engines/dynamics2d/chipmunk-physics/src/cpBody.c
daneshtarapore/argos3-asv
208e23bfab382b71dbbb5de1ec3d749e8ae194d3
[ "MIT" ]
null
null
null
src/plugins/simulator/physics_engines/dynamics2d/chipmunk-physics/src/cpBody.c
daneshtarapore/argos3-asv
208e23bfab382b71dbbb5de1ec3d749e8ae194d3
[ "MIT" ]
null
null
null
/* Copyright (c) 2007 Scott Lembcke * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdlib.h> #include <float.h> #include <math.h> #include <stdio.h> #include "chipmunk_private.h" #include "constraints/util.h" // initialized in cpInitChipmunk() cpBody cpStaticBodySingleton; cpBody* cpBodyAlloc(void) { return (cpBody *)cpcalloc(1, sizeof(cpBody)); } cpBody * cpBodyInit(cpBody *body, cpFloat m, cpFloat i) { body->space = NULL; body->shapeList = NULL; body->arbiterList = NULL; body->constraintList = NULL; body->velocity_func = cpBodyUpdateVelocity; body->position_func = cpBodyUpdatePosition; body->ControlledBody = NULL; cpComponentNode node = {NULL, NULL, 0.0f}; body->node = node; body->p = cpvzero; body->v = cpvzero; body->vl = cpvzero; body->v_dot = cpvzero; body->f = cpvzero; body->w = 0.0f; body->w_dot = 0.0f; body->t = 0.0f; body->v_bias = cpvzero; body->w_bias = 0.0f; body->v_limit = (cpFloat)INFINITY; body->w_limit = (cpFloat)INFINITY; body->data = NULL; // Setters must be called after full initialization so the sanity checks don't assert on garbage data. cpBodySetMass(body, m); cpBodySetMoment(body, i); cpBodySetAngle(body, 0.0f); return body; } cpBody* cpBodyNew(cpFloat m, cpFloat i) { return cpBodyInit(cpBodyAlloc(), m, i); } cpBody * cpBodyInitStatic(cpBody *body) { cpBodyInit(body, (cpFloat)INFINITY, (cpFloat)INFINITY); body->node.idleTime = (cpFloat)INFINITY; return body; } cpBody * cpBodyNewStatic() { return cpBodyInitStatic(cpBodyAlloc()); } void cpBodyDestroy(cpBody *body){} void cpBodyFree(cpBody *body) { if(body){ cpBodyDestroy(body); cpfree(body); } } static void cpv_assert_nan(cpVect v, char *message){cpAssertSoft(v.x == v.x && v.y == v.y, message);} static void cpv_assert_infinite(cpVect v, char *message){cpAssertSoft(cpfabs(v.x) != INFINITY && cpfabs(v.y) != INFINITY, message);} static void cpv_assert_sane(cpVect v, char *message){cpv_assert_nan(v, message); cpv_assert_infinite(v, message);} #ifdef __cplusplus extern "C" { #endif void cpBodySanityCheck(cpBody *body) { cpAssertSoft(body->m == body->m && body->m_inv == body->m_inv, "Body's mass is invalid."); cpAssertSoft(body->i == body->i && body->i_inv == body->i_inv, "Body's moment is invalid."); cpv_assert_sane(body->p, "Body's position is invalid."); cpv_assert_sane(body->v, "Body's velocity is invalid."); cpv_assert_sane(body->f, "Body's force is invalid."); cpAssertSoft(body->a == body->a && cpfabs(body->a) != INFINITY, "Body's angle is invalid."); cpAssertSoft(body->w == body->w && cpfabs(body->w) != INFINITY, "Body's angular velocity is invalid."); cpAssertSoft(body->t == body->t && cpfabs(body->t) != INFINITY, "Body's torque is invalid."); cpv_assert_sane(body->rot, "Internal error: Body's rotation vector is invalid."); cpAssertSoft(body->v_limit == body->v_limit, "Body's velocity limit is invalid."); cpAssertSoft(body->w_limit == body->w_limit, "Body's angular velocity limit is invalid."); } #ifdef __cplusplus } #endif void cpBodySetMass(cpBody *body, cpFloat mass) { cpBodyActivate(body); body->m = mass; body->m_inv = 1.0f/mass; } void cpBodySetMoment(cpBody *body, cpFloat moment) { cpBodyActivate(body); body->i = moment; body->i_inv = 1.0f/moment; } void cpBodyAddShape(cpBody *body, cpShape *shape) { cpShape *next = body->shapeList; if(next) next->prev = shape; shape->next = next; body->shapeList = shape; } void cpBodyRemoveShape(cpBody *body, cpShape *shape) { cpShape *prev = shape->prev; cpShape *next = shape->next; if(prev){ prev->next = next; } else { body->shapeList = next; } if(next){ next->prev = prev; } shape->prev = NULL; shape->next = NULL; } static cpConstraint * filterConstraints(cpConstraint *node, cpBody *body, cpConstraint *filter) { if(node == filter){ return cpConstraintNext(node, body); } else if(node->a == body){ node->next_a = filterConstraints(node->next_a, body, filter); } else { node->next_b = filterConstraints(node->next_b, body, filter); } return node; } void cpBodyRemoveConstraint(cpBody *body, cpConstraint *constraint) { body->constraintList = filterConstraints(body->constraintList, body, constraint); } void cpBodySetPos(cpBody *body, cpVect pos) { cpBodyActivate(body); cpBodyAssertSane(body); body->p = pos; } static inline void setAngle(cpBody *body, cpFloat angle) { body->a = angle;//fmod(a, (cpFloat)M_PI*2.0f); body->rot = cpvforangle(angle); } void cpBodySetAngle(cpBody *body, cpFloat angle) { cpBodyActivate(body); cpBodyAssertSane(body); setAngle(body, angle); } void cpBodyUpdateVelocity(cpBody *body, cpVect gravity, cpFloat damping, cpFloat dt) { // cpASVBodyInverseDynamics(body); // //printf("\n cpBodyUpdateVelocity body->v_dot: <%f %f>; \n",body->v_dot.x, body->v_dot.y); // body->v = cpvadd(body->v, cpvmult(body->v_dot, dt)); // body->w = body->w + body->w_dot * dt; // //printf("\n cpBodyUpdateVelocity body->v: <%f %f>; \n",body->v.x, body->v.y); body->v = cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)); body->v = cpvclamp(cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)), body->v_limit); cpFloat w_limit = body->w_limit; body->w = cpfclamp(body->w*damping + body->t*body->i_inv*dt, -w_limit, w_limit); cpBodySanityCheck(body); } void cpBodyUpdatePosition(cpBody *body, cpFloat dt) { //printf("\ndt in cpBodyUpdatePosition %f\n body->v_bias is %f,%f \n", dt, body->v_bias.x, body->v_bias.y); //printf("\n cpBodyUpdatePosition body->v: <%f %f>; \n",body->v.x, body->v.y); body->p = cpvadd(body->p, cpvmult(cpvadd(body->v, body->v_bias), dt)); setAngle(body, body->a + (body->w + body->w_bias)*dt); //printf("\n cpBodyUpdatePosition body->p: <%f %f>; \n",body->p.x, body->p.y); body->v_bias = cpvzero; body->w_bias = 0.0f; cpBodySanityCheck(body); } void cpBodyResetForces(cpBody *body) { cpBodyActivate(body); body->f = cpvzero; body->t = 0.0f; } void cpBodyApplyForce(cpBody *body, cpVect force, cpVect r) { cpBodyActivate(body); body->f = cpvadd(body->f, force); body->t += cpvcross(r, force); } void cpBodyApplyImpulse(cpBody *body, const cpVect j, const cpVect r) { cpBodyActivate(body); apply_impulse(body, j, r); } void cpBodyEachShape(cpBody *body, cpBodyShapeIteratorFunc func, void *data) { cpShape *shape = body->shapeList; while(shape){ cpShape *next = shape->next; func(body, shape, data); shape = next; } } void cpBodyEachConstraint(cpBody *body, cpBodyConstraintIteratorFunc func, void *data) { cpConstraint *constraint = body->constraintList; while(constraint){ cpConstraint *next = cpConstraintNext(constraint, body); func(body, constraint, data); constraint = next; } } void cpBodyEachArbiter(cpBody *body, cpBodyArbiterIteratorFunc func, void *data) { cpArbiter *arb = body->arbiterList; while(arb){ cpArbiter *next = cpArbiterNext(arb, body); arb->swappedColl = (body == arb->body_b); func(body, arb, data); arb = next; } } void cpASVBodyInverseDynamics(cpBody *body) { //printf("\n cpASVBodyInverseDynamics body->asv_parameters.tt: <%f %f %f>; \n",body->asv_parameters.t_11, body->asv_parameters.t_21, body->asv_parameters.t_31); // Convert velocity vector from world to local coordinate frame //cpVect vl = cpvunrotate(body->v, body->rot); // Compute acceleration in local coordinate frame body->v_dot.x = body->asv_parameters.m_inv11 * (body->asv_parameters.t_11 - body->vl.x * body->asv_parameters.xu2 + body->w * (body->w * body->asv_parameters.yr1 + body->vl.y * (body->asv_parameters.m + body->asv_parameters.yv1)) - body->vl.x * body->asv_parameters.xu3 * abs(body->vl.x)); body->v_dot.y = body->asv_parameters.m_inv22 * (body->asv_parameters.t_21 - body->w * body->vl.x * (body->asv_parameters.m + body->asv_parameters.xu1) - body->vl.y * body->asv_parameters.yv2 - body->vl.y * body->asv_parameters.yv3 * abs(body->vl.y)); body->w_dot = body->asv_parameters.m_inv33 * (body->asv_parameters.t_31 - body->asv_parameters.nr2 * body->w + body->vl.x * body->vl.y * body->asv_parameters.xu1 - body->w * body->vl.x * body->asv_parameters.yr1 - body->vl.x * body->vl.y * body->asv_parameters.yv1 - body->asv_parameters.nr3 * body->w * abs(body->w)); } void cpControlBodyUpdateVelocity(cpBody *body, cpFloat dt) { // Compute acceleration in local coordinate frame cpASVBodyInverseDynamics(body); //printf("\n cpBodyUpdateVelocity body->vlocal_dot: <%f %f>; \n",body->v_dot.x, body->v_dot.y); // Convert velocity vector from world to local coordinate frame // cpVect vl = cpvunrotate(body->v, body->rot); // Compute new velocity vector and then convert to world coordinate frame body->vl = cpvadd(body->vl, cpvmult(body->v_dot, dt)); body->w = body->w + body->w_dot * dt; body->v = cpvrotate(body->vl, body->ControlledBody->rot); //body->v.x = cos(body->a)*body->vl.x - sin(body->a)*body->vl.y; //body->v.y = sin(body->a)*body->vl.x + cos(body->a)*body->vl.y; //printf("\n cpBodyUpdateVelocity body->v: <%f %f>; \n",body->v.x, body->v.y); /*body->v = cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)); body->v = cpvclamp(cpvadd(cpvmult(body->v, damping), cpvmult(cpvadd(gravity, cpvmult(body->f, body->m_inv)), dt)), body->v_limit); cpFloat w_limit = body->w_limit; body->w = cpfclamp(body->w*damping + body->t*body->i_inv*dt, -w_limit, w_limit);*/ cpBodySanityCheck(body); }
27.13602
164
0.685046
[ "shape", "vector" ]
c0ae5db47d71ab9f6438def07f940e991db6f872
3,229
h
C
xspec/XSModel/Parameter/ResponseParam.h
DougBurke/xspeclmodels
4e9caf971af51ab88eb0f8cf678a11f014710013
[ "CC0-1.0" ]
null
null
null
xspec/XSModel/Parameter/ResponseParam.h
DougBurke/xspeclmodels
4e9caf971af51ab88eb0f8cf678a11f014710013
[ "CC0-1.0" ]
null
null
null
xspec/XSModel/Parameter/ResponseParam.h
DougBurke/xspeclmodels
4e9caf971af51ab88eb0f8cf678a11f014710013
[ "CC0-1.0" ]
null
null
null
// Read the documentation to learn more about C++ code generator // versioning. // %X% %Q% %Z% %W% #ifndef RESPONSEPARAM_H #define RESPONSEPARAM_H 1 // Response #include <XSModel/Data/Detector/Response.h> // ModParam #include <XSModel/Parameter/ModParam.h> class ResponseParam : public ModParam //## Inherits: <unnamed>%414999C30367 { public: ResponseParam (const string& initString, Response* responseParent, Response::ResponseParType parType); ~ResponseParam(); virtual ResponseParam* clone (Component* p = 0) const; virtual void freeze (); virtual void rePrompt (string& newString) const; // Note: Unless isPrompt flag is set to true, this will // automatically call parent's applyGainFromFit function // for key values a,v,z. virtual int setValue (Real val, const char key = 'v'); virtual void setCompute (bool flag) const; Response* responseParent (); const Response* responseParent () const; // reset parameter value to its initial values. // // This is a virtual function whose default implementation // is to assume that the parameter is defined in XSPEC's // model.{version} file. virtual void reset (); // This is called when the response param to which this is // linked gets changed. It needs to tell its Response // parent to apply a new gain. void reevaluateLink () const; // Essentially a wrapper around the Parameter::modify // function, this ensures the isPrompt flag is set to true // when the values are changed (preventing an applyGainFrom // Fit call), and restores it to false even in the event of // an exception. Also any leading whitespace is removed // from paramStr prior to calling modify. void setValuesFromString (const string& paramStr); // Constructs a string from the source number and parameter // index, useful for Fit output column headings. virtual string getParameterLabel () const; Response::ResponseParType parType () const; bool isPrompt () const; void isPrompt (bool value); // Additional Public Declarations protected: virtual void changeValue (const string& parString); virtual bool processValues (const string& parString); virtual std::ostream& put (std::ostream& s) const; // Additional Protected Declarations private: ResponseParam(); ResponseParam & operator=(const ResponseParam &right); // Additional Private Declarations private: //## implementation // Data Members for Class Attributes Response* const m_responseParent; Response::ResponseParType m_parType; bool m_isPrompt; // Additional Implementation Declarations }; // Class ResponseParam inline Response* ResponseParam::responseParent () { return m_responseParent; } inline const Response* ResponseParam::responseParent () const { return m_responseParent; } inline Response::ResponseParType ResponseParam::parType () const { return m_parType; } inline bool ResponseParam::isPrompt () const { return m_isPrompt; } inline void ResponseParam::isPrompt (bool value) { m_isPrompt = value; } #endif
29.09009
108
0.693713
[ "model" ]
c0bf0b54313463ac645d914d00a50135b192b307
1,280
h
C
Ass2/src/Transform.h
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Ass2/src/Transform.h
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
Ass2/src/Transform.h
LAK132/OpenGL-Trash
9ddedf65792de78f642f47ad032b5027e4c390c1
[ "MIT" ]
null
null
null
// Transform header file to define the interface. // The class is all static for simplicity // You need to implement left, up and lookAt // Rotate is a helper function // Include the helper glm library, including matrix transform extensions #ifndef GLM_FORCE_RADIANS #define GLM_FORCE_RADIANS #endif #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> // glm provides vector, matrix classes like glsl // Typedefs to make code more readable typedef glm::mat3 mat3 ; typedef glm::mat4 mat4 ; typedef glm::vec3 vec3 ; typedef glm::vec4 vec4 ; const float pi = 3.14159265 ; // For portability across platforms class Transform { public: Transform(); virtual ~Transform(); static void left(float degrees, vec3& eye, vec3& up); static void up(float degrees, vec3& eye, vec3& up); static mat4 lookAt(const vec3& eye, const vec3 &center, const vec3& up); static mat4 perspective(float fovy, float aspect, float zNear, float zFar); static mat3 rotate(const float degrees, const vec3& axis) ; static mat3 rotate(const float degrees, vec3&& axis) ; static mat4 scale(const float &sx, const float &sy, const float &sz) ; static mat4 translate(const float &tx, const float &ty, const float &tz); static vec3 upvector(const vec3 &up, const vec3 &zvec) ; };
32
76
0.739063
[ "vector", "transform" ]
c0c715dd7a2024d22af791769f1d1a29ea229c3a
1,447
h
C
include/numeric.h
linux2647/yahtzee
4255fe1c937565ac3590463e20c79f7833f3d278
[ "BSD-2-Clause" ]
null
null
null
include/numeric.h
linux2647/yahtzee
4255fe1c937565ac3590463e20c79f7833f3d278
[ "BSD-2-Clause" ]
null
null
null
include/numeric.h
linux2647/yahtzee
4255fe1c937565ac3590463e20c79f7833f3d278
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************** * Copyright (c) 2014, Stephen Howell * * All rights reserved. * ******************************************************************************/ #ifndef NUMERIC_H #define NUMERIC_H #include "score_slot.h" /** * Generic numeric scoring object. * * Dice are scored based on the number of dice with the same value as the * scoring object. The exact score is the number of dice with the value * multiplied by the value. */ class Numeric : public ScoreSlot { int _value; bool _filled; int _score; public: /** * Constructs a generic numeric scoring object * * @param value The value that dice should be scored against. */ Numeric(int value) : _value(value), _filled(false), _score(0) {}; /** * Scores a set of dice. * * @param dice Dice used for scoring. * @return Resultant score. */ int score(std::vector<Die>); /** * Returns the name for the scoring slot. */ const std::string getName(); /** * Returns whether or not the slot has been used. */ bool isFilled(); /** * Returns the score of the slot. * * Calling this when isFilled() returns false results in undefined behavior. */ int getScore(); }; #endif // NUMERIC_H
24.525424
80
0.508639
[ "object", "vector" ]
c0cc15ebb180719d5b040ea7a390a26af88f2bf1
679
h
C
Sources/Kore/Vr/CameraImage.h
hyperluminality/Kinc
f1802becc92e9a9eaa2e13b205d6a18eb58359a3
[ "Zlib" ]
1
2020-11-11T15:11:27.000Z
2020-11-11T15:11:27.000Z
Sources/Kore/Vr/CameraImage.h
hyperluminality/Kinc
f1802becc92e9a9eaa2e13b205d6a18eb58359a3
[ "Zlib" ]
null
null
null
Sources/Kore/Vr/CameraImage.h
hyperluminality/Kinc
f1802becc92e9a9eaa2e13b205d6a18eb58359a3
[ "Zlib" ]
null
null
null
#pragma once #include <Kore/Math/Quaternion.h> #include <Kore/Math/Vector.h> class CameraImage { public: CameraImage(int imageHeight, int imageWidth, int* imageBGRA8Data, Kore::mat4 cameraViewTransform, Kore::mat4 cameraProjectionTransform, Kore::vec2 focalLength); ~CameraImage(); int* imageBGRA8Data; int imageWidth, imageHeight; // in world (root) coordinate system Kore::mat4 cameraViewTransform; Kore::mat4 cameraProjectionTransform; Kore::vec2 focalLength; void getWorldRayForPixelPosition(Kore::vec2 pixelPosition, Kore::vec3& origin, Kore::vec3& direction); // origin at camera pos Kore::vec2 getPixelForWorldPosition(Kore::vec3 worldPos); };
30.863636
136
0.765832
[ "vector" ]
c0cdbb69b99f1b519f0afba8ec06999fdd1e53b7
68,366
h
C
public/internal/windows/inc/shimdb.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/published/shimdb.w
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/published/shimdb.w
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*-- Copyright (c) Microsoft Corporation. All rights reserved. Module Name: shimdb.h Abstract: header for the database file access functions used by the App Compat shimming system Author: dmunsil 02/02/2000 Revision History: Notes: This "database" is more of a tagged file, designed to mimic the structure of an XML file. An XML file can be converted into this packed data format easily, and all strings will by default be packed into a stringtable and referenced by a DWORD identifier, so files that contain a lot of common strings (like the XML used by the App Compat tema) will not bloat. To see the actual tags used by the shimdb, look in shimtags.h. For the high-level interface used by the loader in NTDLL, look at ntbaseapi.c --*/ #ifndef _SHIMDB_H_ #define _SHIMDB_H_ /*++ Supported configurations: UNICODE with NT apis ANSI with WIN32 apis By default the library is UNICODE To use (and link) Win32 library --*/ #ifdef SDB_ANSI_LIB #define LPCTSTR LPCSTR #define LPTSTR LPSTR #define TCHAR CHAR #else #define LPCTSTR LPCWSTR #define LPTSTR LPWSTR #define TCHAR WCHAR #endif #define SDBAPI STDAPICALLTYPE typedef WORD TAG; typedef WORD TAG_TYPE; typedef DWORD TAGID; typedef DWORD TAG_OFFSET; typedef DWORD STRINGREF; typedef DWORD INDEXID; #define TAGID_NULL 0 #define STRINGREF_NULL 0 #define INDEXID_NULL ((INDEXID)-1) #define TAG_NULL 0 #define TAGID_ROOT 0 // implied root list tag that can be passed in as a parent #define TAG_SIZE_UNFINISHED 0xFFFFFFFF // // define TAGREF so we can use tags accross databases // typedef DWORD TAGREF; /////////////////////////////////////////////////////////////////////////////// // // TAG TYPES // // // The most significant 4 bits tell you the basic type and size of data, // and the lower 12 are the specific tag. // // In this way, even if we add more tags to the db, older readers can read // the data because the type is either implied (for the first 5 types) // or supplied (for all other types). // // WARNING: it is important that only the first 5 types have implied sizes. // any future types should use a size or backwards compatibility will not be // maintained. // // The following tags have an implied size. // #define TAG_TYPE_NULL 0x1000 // implied size 0 #define TAG_TYPE_BYTE 0x2000 // implied size 1 #define TAG_TYPE_WORD 0x3000 // implied size 2 #define TAG_TYPE_DWORD 0x4000 // implied size 4 #define TAG_TYPE_QWORD 0x5000 // implied size 8 #define TAG_TYPE_STRINGREF 0x6000 // implied size 4, for strings that should be tokenized // // These tags have a size after them (the size is type TAG_OFFSET) // #define TAG_TYPE_LIST 0x7000 #define TAG_TYPE_STRING 0x8000 #define TAG_TYPE_BINARY 0x9000 #define TAGREF_NULL 0 #define TAGREF_ROOT 0 // // Special define for stripping out just the type from a tag. // #define TAG_STRIP_TYPE 0xF000 // // This macro strips off the lower bits of the TAG and returns the upper bits, which // give the basic type of tag. All the tag types are defined above. // // The type info is purely used internally by the DB to tell whether the tag has // an implied size, or if the DB needs to do something special with the data before // handing it back to the caller. // #define GETTAGTYPE(tag) ((tag) & TAG_STRIP_TYPE) typedef PVOID HSDB; struct tagHOOKAPI; typedef struct tagHOOKAPIEX { DWORD dwShimID; struct tagHOOKAPI* pTopOfChain; struct tagHOOKAPI* pNext; } HOOKAPIEX, *PHOOKAPIEX; typedef struct tagHOOKAPI { char* pszModule; // the name of the module char* pszFunctionName; // the name of the API in the module PVOID pfnNew; // pointer to the new stub API PVOID pfnOld; // pointer to the old API DWORD dwFlags; // used internally - important info about status union { struct tagHOOKAPI* pNextHook; // used internally - (obsolete -- old mechanism) PHOOKAPIEX pHookEx; // used internally - pointer to an internal extended // info struct }; } HOOKAPI, *PHOOKAPI; // // OBSOLETE ! // // If the hook DLL ever patches LoadLibraryA/W it must call PatchNewModules // so that the shim knows to patch any new loaded DLLs // typedef VOID (*PFNPATCHNEWMODULES)(VOID); typedef PHOOKAPI (*PFNGETHOOKAPIS)(LPSTR pszCmdLine, LPWSTR pwszShim, DWORD* pdwHooksCount); // // These structures are part of the protocol between NTVDM and the shim engine // for patching task "import tables" // typedef struct tagAPIDESC { char* pszModule; char* pszApi; } APIDESC, *PAPIDESC; typedef struct tagVDMTABLE { int nApiCount; PVOID* ppfnOrig; APIDESC* pApiDesc; } VDMTABLE, *PVDMTABLE; // // Shim engine notification events // #define SN_STATIC_DLLS_INITIALIZED 1 #define SN_PROCESS_DYING 2 #define SN_DLL_LOADING 3 // // This is the prototype for the notification function // that the shim engine calls into the shim DLLs for various // reasons (defined above). // typedef void (*PFNNOTIFYSHIMS)(int nReason, UINT_PTR extraInfo); #define SHIM_COMMAND_LINE_MAX_BUFFER 1024 /////////////////////////////////////////////////////////////////////////////// // // PATCH STRUCTURES // typedef struct _PATCHOP { DWORD dwOpcode; // Opcode to be performed DWORD dwNextOpcode; // Relative offset to next opcode #pragma warning( disable : 4200 ) BYTE data[]; // Data for this operation type is dependent // on the op-code. #pragma warning( default : 4200 ) } PATCHOP, *PPATCHOP; typedef struct _RELATIVE_MODULE_ADDRESS { DWORD address; // Relative address from beginning of loaded module BYTE reserved[3]; // Reserved for system use WCHAR moduleName[32]; // Module name for this address. } RELATIVE_MODULE_ADDRESS, *PRELATIVE_MODULE_ADDRESS; typedef struct _PATCHWRITEDATA { DWORD dwSizeData; // Size of patch data in bytes RELATIVE_MODULE_ADDRESS rva; // Relative address where this patch data is // to be applied. #pragma warning( disable : 4200 ) BYTE data[]; // Patch data bytes. #pragma warning( default : 4200 ) } PATCHWRITEDATA, *PPATCHWRITEDATA; typedef struct _PATCHMATCHDATA { DWORD dwSizeData; // Size of matching data data in bytes RELATIVE_MODULE_ADDRESS rva; // Relative address where this patch data is // to be verified. #pragma warning( disable : 4200 ) BYTE data[]; // Matching data bytes. #pragma warning( default : 4200 ) } PATCHMATCHDATA, *PPATCHMATCHDATA; typedef enum _PATCHOPCODES { PEND = 0, // no more opcodes PSAA, // Set Activate Address, SETACTIVATEADDRESS PWD, // Patch Write Data, PATCHWRITEDATA PNOP, // No Operation PMAT, // Patch match the matching bytes but do not replace the bytes. } PATCHOPCODES; // // HEADER STRUCTURE // #define SHIMDB_MAGIC 0x66626473 // 'sdbf' (reversed because of little-endian ordering) #define SHIMDB_MAJOR_VERSION 2 // Don't change this unless fundamentals // change (like TAG size, etc.) #define SHIMDB_MINOR_VERSION 0 // This is for info only -- ignored on read typedef struct _DB_HEADER { DWORD dwMajorVersion; DWORD dwMinorVersion; DWORD dwMagic; } DB_HEADER, *PDB_HEADER; // // INDEX_RECORD STRUCTURE // #pragma pack (push, 4) typedef struct _INDEX_RECORD { ULONGLONG ullKey; TAGID tiRef; } INDEX_RECORD; typedef INDEX_RECORD UNALIGNED *PINDEX_RECORD; #pragma pack (pop) // // Forward declaration. // struct _DB; typedef struct _DB* PDB; // // This flag is used in apphelp entries. // When set, it denotes entries that only have apphelp information. // #define SHIMDB_APPHELP_ONLY 0x00000001 typedef enum _PATH_TYPE { DOS_PATH, NT_PATH } PATH_TYPE; typedef struct _FIND_INFO { TAGID tiIndex; TAGID tiCurrent; TAGID tiEndIndex; // last record after FindFirst if index is UNIQUE TAG tName; DWORD dwIndexRec; DWORD dwFlags; ULONGLONG ullKey; // calculated key for this entry union { LPCTSTR szName; DWORD dwName; // for dword search GUID* pguidName; }; } FIND_INFO, *PFIND_INFO; #define SDB_MAX_LAYERS 8 #define SDB_MAX_EXES 4 #define SDB_MAX_SDBS 16 typedef struct tagSDBQUERYRESULT { TAGREF atrExes[SDB_MAX_EXES]; TAGREF atrLayers[SDB_MAX_LAYERS]; DWORD dwLayerFlags; TAGREF trAppHelp; // If there is an apphelp to display, the EXE // entry will be here. DWORD dwExeCount; // number of elements in atrexes DWORD dwLayerCount; // number of elements in atrLayers GUID guidID; // last exe's GUID DWORD dwFlags; // last exe's flags // // New entries are here to preserve compatibility. // Only some entries will be valid in this map. // DWORD dwCustomSDBMap; // entry map, technically not needed GUID rgGuidDB[SDB_MAX_SDBS]; } SDBQUERYRESULT, *PSDBQUERYRESULT; // // Information related to TAG_DRIVER tag in the db. // Use SdbReadDriverInformation to retrieve this struct. // typedef struct tagENTRYINFO { GUID guidID; // guid ID for this entry DWORD dwFlags; // registry flags for this exe TAGID tiData; // optional id for a TAG_DATA tag GUID guidDB; // optional guid for the database where // this entry is located } SDBENTRYINFO, *PSDBENTRYINFO; // // Flags used by SDBDATABASEINFO.dwFlags // #define DBINFO_GUID_VALID 0x00000001 #define DBINFO_SDBALLOC 0x10000000 typedef struct tagSDBDATABASEINFO { DWORD dwFlags; // flags -- which struct members are valid (and // perhaps flags relevant to db content in the future DWORD dwVersionMajor; // major version DWORD dwVersionMinor; // minor version (time stamp) LPTSTR pszDescription; // description, optional GUID guidDB; // database id } SDBDATABASEINFO, *PSDBDATABASEINFO; #if defined(_WIN64) #define DEFAULT_IMAGE IMAGE_FILE_MACHINE_IA64 #else #define DEFAULT_IMAGE IMAGE_FILE_MACHINE_I386 #endif // // special image type -- which represents a mixture of image types // depending on the component. It is used (as name implies) by MSI // this value is not used by any of the IMAGE_FILE_MACHINE_* constants // #define IMAGE_FILE_MSI 0x7FFF /////////////////////////////////////////////////////////////////////////////// // // APIs to read/write/access the shim database // // // READ functions // BYTE SDBAPI SdbReadBYTETag( IN PDB pdb, IN TAGID tiWhich, IN BYTE jDefault ); WORD SDBAPI SdbReadWORDTag( IN PDB pdb, IN TAGID tiWhich, IN WORD wDefault ); DWORD SDBAPI SdbReadDWORDTag( IN PDB pdb, IN TAGID tiWhich, IN DWORD dwDefault ); ULONGLONG SDBAPI SdbReadQWORDTag( IN PDB pdb, IN TAGID tiWhich, IN ULONGLONG qwDefault ); BOOL SDBAPI SdbReadBinaryTag( IN PDB pdb, IN TAGID tiWhich, OUT PBYTE pBuffer, IN DWORD dwBufferSize ); BOOL SDBAPI SdbReadStringTag( IN PDB pdb, IN TAGID tiWhich, OUT LPTSTR pwszBuffer, IN DWORD cchBufferSize ); LPTSTR SDBAPI SdbGetStringTagPtr( IN PDB pdb, IN TAGID tiWhich ); BYTE SDBAPI SdbReadBYTETagRef( IN HSDB hSDB, IN TAGREF trWhich, IN BYTE jDefault ); WORD SDBAPI SdbReadWORDTagRef( IN HSDB hSDB, IN TAGREF trWhich, IN WORD wDefault ); DWORD SDBAPI SdbReadDWORDTagRef( IN HSDB hSDB, IN TAGREF trWhich, IN DWORD dwDefault ); ULONGLONG SDBAPI SdbReadQWORDTagRef( IN HSDB hSDB, IN TAGREF trWhich, IN ULONGLONG qwDefault ); BOOL SDBAPI SdbReadStringTagRef( IN HSDB hSDB, IN TAGREF trWhich, OUT LPTSTR pwszBuffer, IN DWORD cchBufferSize ); // // GENERAL ACCESS FUNCTIONS // TAGID SDBAPI SdbGetFirstChild( IN PDB pdb, IN TAGID tiParent ); TAGID SDBAPI SdbGetNextChild( IN PDB pdb, IN TAGID tiParent, IN TAGID tiPrev ); TAG SDBAPI SdbGetTagFromTagID( IN PDB pdb, IN TAGID tiWhich ); DWORD SDBAPI SdbGetTagDataSize( IN PDB pdb, IN TAGID tiWhich ); PVOID SDBAPI SdbGetBinaryTagData( IN PDB pdb, IN TAGID tiWhich ); BOOL SDBAPI SdbIsTagrefFromMainDB( TAGREF trWhich ); BOOL SDBAPI SdbIsTagrefFromLocalDB( TAGREF trWhich ); typedef struct tagATTRINFO *PATTRINFO; ////////////////////////////////////////////////////////////////////////// // Grab Matching Information Function Declaration // // // Filters available for SdbGrabMatchingInfo // #define GRABMI_FILTER_NORMAL 0 #define GRABMI_FILTER_PRIVACY 1 #define GRABMI_FILTER_DRIVERS 2 #define GRABMI_FILTER_VERBOSE 3 #define GRABMI_FILTER_SYSTEM 4 #define GRABMI_FILTER_THISFILEONLY 5 #define GRABMI_FILTER_NOCLOSE 0x10000000 #define GRABMI_FILTER_APPEND 0x20000000 #define GRABMI_FILTER_LIMITFILES 0x40000000 #define GRABMI_FILTER_NORECURSE 0x80000000 #define GRABMI_IMPOSED_FILE_LIMIT 25 typedef enum GMI_RESULT { GMI_FAILED = FALSE, GMI_SUCCESS = TRUE, GMI_CANCELLED = -1 } GMI_RESULT; BOOL SDBAPI SdbGrabMatchingInfo( LPCTSTR szMatchingPath, DWORD dwFilter, LPCTSTR szFile ); typedef BOOL (CALLBACK* PFNGMIProgressCallback)( LPVOID lpvCallbackParam, // application-defined parameter LPCTSTR lpszRoot, // root directory path LPCTSTR lpszRelative, // relative path PATTRINFO pAttrInfo, // attributes LPCWSTR pwszXML // resulting xml ); GMI_RESULT SDBAPI SdbGrabMatchingInfoEx( LPCTSTR szMatchingPath, DWORD dwFilter, LPCTSTR szFile, PFNGMIProgressCallback pfnCallback, LPVOID lpvCallbackParam ); // // Module-type constants // #define MT_UNKNOWN_MODULE 0 #define MT_DOS_MODULE 1 #define MT_W16_MODULE 2 #define MT_W32_MODULE 3 ////////////////////////////////////////////////////////////////////////// // // TAGREF functions // ////////////////////////////////////////////////////////////////////////// BOOL SDBAPI SdbTagIDToTagRef( IN HSDB hSDB, IN PDB pdb, IN TAGID tiWhich, OUT TAGREF* ptrWhich ); BOOL SDBAPI SdbTagRefToTagID( IN HSDB hSDB, IN TAGREF trWhich, OUT PDB* ppdb, OUT TAGID* ptiWhich ); // // SEARCH functions // TAGID SDBAPI SdbFindFirstTag( IN PDB pdb, IN TAGID tiParent, IN TAG tTag ); TAGID SDBAPI SdbFindNextTag( IN PDB pdb, IN TAGID tiParent, IN TAGID tiPrev ); TAGID SDBAPI SdbFindFirstNamedTag( IN PDB pdb, IN TAGID tiParent, IN TAG tToFind, IN TAG tName, IN LPCTSTR pszName ); TAGREF SDBAPI SdbFindFirstTagRef( IN HSDB hSDB, IN TAGREF trParent, IN TAG tTag ); TAGREF SDBAPI SdbFindNextTagRef( IN HSDB hSDB, IN TAGREF trParent, IN TAGREF trPrev ); // // DB access APIs // // // Flags for SdbInitDatabase. // #define HID_DOS_PATHS 0x00000001 // use DOS paths #define HID_DATABASE_FULLPATH 0x00000002 // pszDatabasePath is a full path to the main db #define HID_NO_DATABASE 0x00000004 // do not open database at this time #define HID_DATABASE_TYPE_MASK 0xF00F0000 // mask that shows whether we have any // database type-related bits // // The flags could be OR'd with SDB_DATABASE_* bits // HSDB SDBAPI SdbInitDatabase( IN DWORD dwFlags, IN LPCTSTR pszDatabasePath ); HSDB SDBAPI SdbInitDatabaseEx( IN DWORD dwFlags, IN LPCTSTR pszDatabasePath, IN USHORT uExeType ); VOID SDBAPI SdbSetImageType( IN HSDB hSDB, IN USHORT uExeType ); HSDB SDBAPI SdbInitDatabaseInMemory( IN LPVOID pDatabaseImage, IN DWORD dwImageSize ); VOID SDBAPI SdbReleaseDatabase( IN HSDB hSDB ); // // Information - retrieval functions // BOOL SDBAPI SdbGetDatabaseVersion( IN LPCTSTR pwszFileName, OUT LPDWORD lpdwMajor, OUT LPDWORD lpdwMinor ); BOOL SDBAPI SdbGetDatabaseInformation( IN PDB pdb, OUT PSDBDATABASEINFO pSdbInfo ); BOOL SDBAPI SdbGetDatabaseID( IN PDB pdb, OUT GUID* pguidDB ); DWORD SDBAPI SdbGetDatabaseDescription( IN PDB pdb, OUT LPTSTR pszDatabaseDescription, IN DWORD BufferSize ); VOID SDBAPI SdbFreeDatabaseInformation( IN PSDBDATABASEINFO pDBInfo ); BOOL SDBAPI SdbGetDatabaseInformationByName( IN LPCTSTR pszDatabase, OUT PSDBDATABASEINFO* ppdbInfo ); #define SDBTYPE_SYSMAIN 0x00000001 #define SDBTYPE_SYSTEST 0x00000002 #define SDBTYPE_MSI 0x00000003 #define SDBTYPE_SHIM 0x00000004 // primarily shim db #define SDBTYPE_APPHELP 0x00000005 // primarily type apphelp #define SDBTYPE_CUSTOM 0x00010000 // this is an "OR" bit // // The function below exists only in user mode on win32 platform // BOOL SDBAPI SdbUnregisterDatabase( IN GUID* pguidDB ); BOOL SDBAPI SdbGetDatabaseRegPath( IN GUID* pguidDB, OUT LPTSTR pszDatabasePath, IN DWORD dwBufferSize // size (in tchars) of the buffer ); ///////////////////////////////////////////////////////////////// // // Database types // for SdbResolveDatabase and SdbRegisterDatabase // // // flag that indicates that the database is the default one // WILL NOT be set for custom databases // #define SDB_DATABASE_MAIN 0x80000000 #define SDB_DATABASE_TEST 0x40000000 // systest.sdb will have 0xc00000000 // // types - one or more apply depending on the contents of the database // (see HID_DATABASE_TYPE values, they should match database types 1:1) #define SDB_DATABASE_SHIM 0x00010000 // set when database contains apps to be fixed by shimming #define SDB_DATABASE_MSI 0x00020000 // set when database contains msi entries #define SDB_DATABASE_DRIVERS 0x00040000 // set when database contains drivers to be blocked #define SDB_DATABASE_DETAILS 0x00080000 // set when the db contains apphelp details #define SDB_DATABASE_TYPE_MASK 0xF00F0000 // // These constants should be used when derefencing "main" databases // #define SDB_DATABASE_MAIN_SHIM (SDB_DATABASE_SHIM | SDB_DATABASE_MSI | SDB_DATABASE_MAIN) #define SDB_DATABASE_MAIN_MSI (SDB_DATABASE_MSI | SDB_DATABASE_MAIN) #define SDB_DATABASE_MAIN_DRIVERS (SDB_DATABASE_DRIVERS | SDB_DATABASE_MAIN) #define SDB_DATABASE_MAIN_TEST (SDB_DATABASE_TEST | SDB_DATABASE_MAIN | SDB_DATABASE_SHIM | SDB_DATABASE_MSI) #define SDB_DATABASE_MAIN_DETAILS (SDB_DATABASE_DETAILS | SDB_DATABASE_MAIN) // // These are internal GUIDs that always reference certain global databases // #define GUID_SZ_SYSMAIN_SDB _T("{11111111-1111-1111-1111-111111111111}"); #define GUID_SZ_APPHELP_SDB _T("{22222222-2222-2222-2222-222222222222}"); #define GUID_SZ_SYSTEST_SDB _T("{33333333-3333-3333-3333-333333333333}"); #define GUID_SZ_DRVMAIN_SDB _T("{F9AB2228-3312-4A73-B6F9-936D70E112EF}"}; // // the following GUIDs are actually declared in sdbapi.c // EXTERN_C const GUID FAR GUID_SYSMAIN_SDB; EXTERN_C const GUID FAR GUID_APPHELP_SDB; EXTERN_C const GUID FAR GUID_SYSTEST_SDB; EXTERN_C const GUID FAR GUID_DRVMAIN_SDB; EXTERN_C const GUID FAR GUID_MSIMAIN_SDB; BOOL SDBAPI SdbGetStandardDatabaseGUID( IN DWORD dwDatabaseType, OUT GUID* pGuidDB ); BOOL SDBAPI SdbRegisterDatabase( IN LPCTSTR pszDatabasePath, IN DWORD dwDatabaseType ); BOOL SDBAPI SdbRegisterDatabaseEx( IN LPCTSTR pszDatabasePath, IN DWORD dwDatabaseType, IN PULONGLONG pTimeStamp ); DWORD SDBAPI SdbResolveDatabase( IN HSDB hSDB, IN GUID* pguidDB, // pointer to the database guid to resolve OUT LPDWORD lpdwDatabaseType, // optional pointer to the database type OUT LPTSTR pszDatabasePath, // optional pointer to the database path IN DWORD dwBufferSize // size of the buffer pszDatabasePath in tchars ); PDB SdbGetPDBFromGUID( IN HSDB hSDB, // HSDB IN GUID* pguidDB // the guid of the DB ); BOOL SdbGetDatabaseGUID( IN HSDB hSDB, // HSDB of the sdbContext (optional) IN PDB pdb, // PDB of the database in question OUT GUID* pguidDB // the guid of the DB ); TAGREF SDBAPI SdbFindMsiPackageByID( IN HSDB hSDB, IN GUID* pguidID ); void SdbpGetAppPatchDir( IN HSDB hSDB, IN LPTSTR szAppPatchPath, IN DWORD cchSize ); // // GUID manipulation apis - not platform dependent // BOOL SDBAPI SdbGUIDFromString( IN LPCTSTR lpszGuid, OUT GUID* pGuid ); BOOL SDBAPI SdbGUIDToString( IN GUID* pGuid, OUT LPTSTR pszGuid, IN DWORD cchSize ); BOOL SDBAPI SdbIsNullGUID( IN GUID* pGuid ); // // open/create and close database. // PDB SDBAPI SdbOpenDatabase( IN LPCTSTR pwszPath, IN PATH_TYPE eType ); BOOL SDBAPI SdbOpenLocalDatabase( IN HSDB hSDB, IN LPCTSTR pwszLocalDatabase ); BOOL SDBAPI SdbCloseLocalDatabase( IN HSDB hSDB ); PDB SDBAPI SdbCreateDatabase( IN LPCWSTR pwszPath, IN PATH_TYPE eType ); void SDBAPI SdbCloseDatabase( IN PDB pdb ); // // Search the database looking for an entry for the specified exe. // // // Flags for SdbGetMatchingExe dwFlags // #define SDBGMEF_IGNORE_ENVIRONMENT 0x00000001 BOOL SdbGetMatchingExe( IN HSDB hSDB OPTIONAL, IN LPCTSTR pwszPath, IN LPCTSTR szModuleName, IN LPCTSTR pwszEnvironment, IN DWORD dwFlags, OUT PSDBQUERYRESULT pQueryResult ); void SdbReleaseMatchingExe( IN HSDB hSDB, IN TAGREF trExe ); TAGREF SDBAPI SdbGetDatabaseMatch( IN HSDB hSDB, IN LPCTSTR szPath, IN HANDLE FileHandle OPTIONAL, IN LPVOID pImageBase OPTIONAL, IN DWORD dwImageSize OPTIONAL ); TAGREF SdbGetLayerTagReg( IN HSDB hSDB, IN LPCTSTR szLayer ); PDB SDBAPI SdbGetLocalPDB( IN HSDB hSDB ); LPTSTR SDBAPI SdbGetLayerName( IN HSDB hSDB, IN TAGREF trLayer ); TAGREF SDBAPI SdbGetNamedLayer( IN HSDB hSDB, // database context IN TAGREF trLayerRef // tagref of a record referencing a layer ); #define SBCE_ADDITIVE 0x00000001 #define SBCE_INCLUDESYSTEMEXES 0x00000002 #define SBCE_INHERITENV 0x00000004 DWORD SdbBuildCompatEnvVariables( IN HSDB hSDB, IN SDBQUERYRESULT* psdbQuery, IN DWORD dwFlags, IN LPCWSTR pwszParentEnv OPTIONAL, // Environment which contains vars we // shall inherit from OUT LPWSTR pBuffer, IN DWORD cbSize, // size of the buffer in tchars OUT LPDWORD lpdwShimsCount OPTIONAL ); // // MSI-specific functionality // typedef enum tagSDBMSILOOKUPSTATE { LOOKUP_NONE = 0, // this should be the first state LOOKUP_LOCAL, LOOKUP_CUSTOM, LOOKUP_TEST, LOOKUP_MAIN, LOOKUP_DONE // this should be the last state } SDBMSILOOKUPSTATE; typedef struct tagSDBMSIFINDINFO { TAGREF trMatch; // tagref of the matching package GUID guidID; // guid of this current package FIND_INFO sdbFindInfo; // standard sdb find info // this is used to persist the state of the current search // SDBMSILOOKUPSTATE sdbLookupState; DWORD dwCustomIndex; } SDBMSIFINDINFO, *PSDBMSIFINDINFO; typedef struct tagSDBMSITRANSFORMINFO { LPCTSTR lpszTransformName; // name of the transform TAGREF trTransform; // tagref of this transform TAGREF trFile; // tagref of file for this transform (bits) } SDBMSITRANSFORMINFO, *PSDBMSITRANSFORMINFO; // // Information for any individual MSI package // typedef struct tagMSIPACKAGEINFO { GUID guidID; // unique guid for this entry GUID guidMsiPackageID; // guid (non-unique, for this entry) GUID guidDatabaseID; // guid of the database where this had been found DWORD dwPackageFlags; // Package flags (see below) } MSIPACKAGEINFO, *PMSIPACKAGEINFO; #define MSI_PACKAGE_HAS_APPHELP 0x00000001 #define MSI_PACKAGE_HAS_SHIMS 0x00000002 TAGREF SDBAPI SdbFindFirstMsiPackage_Str( IN HSDB hSDB, IN LPCTSTR lpszGuid, IN LPCTSTR lpszLocalDB, OUT PSDBMSIFINDINFO pFindInfo ); TAGREF SDBAPI SdbFindFirstMsiPackage( IN HSDB hSDB, // in HSDB context IN GUID* pGuidID, // in GUID that we're looking for IN LPCTSTR lpszLocalDB, // in optional path to local db, dos path style OUT PSDBMSIFINDINFO pFindInfo // pointer to our search context ); TAGREF SDBAPI SdbFindNextMsiPackage( IN HSDB hSDB, IN OUT PSDBMSIFINDINFO pFindInfo ); BOOL SDBAPI SdbGetMsiPackageInformation( IN HSDB hSDB, IN TAGREF trMatch, OUT PMSIPACKAGEINFO pPackageInfo ); DWORD SDBAPI SdbEnumMsiTransforms( IN HSDB hSDB, // in HSDB context IN TAGREF trMatch, // matched entry OUT TAGREF* ptrBuffer, // array of tagrefs to fill with msi transform "fixes" IN OUT DWORD* pdwBufferSize // pointer to the buffer size, receives the number of // bytes written ); BOOL SDBAPI SdbReadMsiTransformInfo( IN HSDB hSDB, // HSDB context IN TAGREF trTransformRef, // reference to a transform, returned // by SdbEnumMsiTransforms OUT PSDBMSITRANSFORMINFO pTransformInfo // information structure ); BOOL SDBAPI SdbCreateMsiTransformFile( IN HSDB hSDB, // context IN LPCTSTR lpszFileName, // filename to write data to IN PSDBMSITRANSFORMINFO pTransformInfo // pointer to the transform structure ); TAGREF SDBAPI SdbFindCustomActionForPackage( IN HSDB hSDB, IN TAGREF trPackage, IN LPCTSTR lpszCustomAction); #define SdbGetFirstMsiTransformForPackage(hSDB, trPackage) \ (SdbFindFirstTagRef((hSDB), (trPackage), TAG_MSI_TRANSFORM_REF)) #define SdbGetNextMsiTransformForPackage(hSDB, trPackage, trPrevMatch) \ (SdbFindNextTagRef((hSDB), (trPackage), (trPrevMatch))) // // "disable" registry entry masks // #define SHIMREG_DISABLE_SHIM 0x00000001 #define SHIMREG_DISABLE_APPHELP 0x00000002 // disables apphelp #define SHIMREG_APPHELP_NOUI 0x00000004 // suppress apphelp ui #define SHIMREG_APPHELP_CANCEL 0x10000000 // returns CANCEL as a default action #define SHIMREG_DISABLE_SXS 0x00000010 #define SHIMREG_DISABLE_LAYER 0x00000020 #define SHIMREG_DISABLE_DRIVER 0x00000040 BOOL SDBAPI SdbSetEntryFlags( IN GUID* pGuidID, IN DWORD dwFlags ); BOOL SDBAPI SdbGetEntryFlags( IN GUID* pGuid, OUT LPDWORD lpdwFlags ); // // Flags used by Get/SetPermLayerKeys // #define GPLK_USER 0x00000001 #define GPLK_MACHINE 0x00000002 #define GPLK_ALL (GPLK_USER | GPLK_MACHINE) BOOL SDBAPI SdbGetPermLayerKeys( LPCTSTR szPath, LPTSTR szLayers, LPDWORD pdwBytes, DWORD dwFlags ); BOOL SDBAPI SdbSetPermLayerKeys( LPCTSTR szPath, LPCTSTR szLayers, BOOL bMachine ); BOOL SDBAPI SdbDeletePermLayerKeys( LPCTSTR szPath, BOOL bMachine ); BOOL SdbGetNthUserSdb( IN HSDB hSDB, // context IN LPCTSTR wszItemName, // item name (foo.exe or layer name) IN BOOL bLayer, // true if layer name IN OUT LPDWORD pdwIndex, // (0-based) OUT GUID* pGuidDB // database guid ); // // APIs to pack/unpack appcompat data package. // BOOL SdbPackAppCompatData( IN HSDB hSDB, IN PSDBQUERYRESULT pSdbQuery, OUT PVOID* ppData, OUT LPDWORD pdwSize ); BOOL SdbUnpackAppCompatData( IN HSDB hSDB, IN LPCWSTR pwszExeName, IN PVOID pAppCompatData, OUT PSDBQUERYRESULT pSdbQuery ); DWORD SdbGetAppCompatDataSize( IN PVOID pAppCompatData ); // // DLL functions // BOOL SdbGetDllPath( IN HSDB hSDB, IN TAGREF trDllRef, OUT LPTSTR pwszBuffer, IN DWORD cchBufferSize ); // // PATCH functions // BOOL SdbReadPatchBits( IN HSDB hSDB, IN TAGREF trPatchRef, OUT PVOID pBuffer, OUT LPDWORD lpdwBufferSize ); // // SDBDRIVERINFO query function // BOOL SDBAPI SdbReadEntryInformation( IN HSDB hSDB, IN TAGREF trDriver, OUT PSDBENTRYINFO pEntryInfo ); DWORD SDBAPI SdbQueryData( IN HSDB hSDB, IN TAGREF trExe, IN LPCTSTR lpszPolicyName, // if this is null, will try to return all the policy names OUT LPDWORD lpdwDataType, OUT LPVOID lpBuffer, // buffer to fill with information IN OUT LPDWORD lpdwBufferSize ); DWORD SDBAPI SdbQueryDataEx( IN HSDB hSDB, // database handle IN TAGREF trExe, // tagref of the matching exe IN LPCTSTR lpszDataName, // if this is null, will try to return all the policy names OUT LPDWORD lpdwDataType, // pointer to data type (REG_SZ, REG_BINARY, etc) OUT LPVOID lpBuffer, // buffer to fill with information IN OUT LPDWORD lpdwBufferSize, // pointer to buffer size OUT TAGREF* ptrData // optional pointer to the retrieved data tag ); DWORD SdbQueryDataExTagID( IN PDB pdb, // database handle IN TAGID tiExe, // tagref of the matching exe IN LPCTSTR lpszDataName, // if this is null, will try to return all the policy names OUT LPDWORD lpdwDataType, // pointer to data type (REG_SZ, REG_BINARY, etc) OUT LPVOID lpBuffer, // buffer to fill with information IN OUT LPDWORD lpcbBufferSize, // pointer to buffer size (in bytes) OUT TAGID* ptiData // optional pointer to the retrieved data tag ); // // Defines to keep kernel-mode code more readable // #define SdbQueryDriverInformation SdbQueryData #define SdbReadDriverInformation SdbReadEntryInformation #define SDBDRIVERINFO SDBENTRYINFO; #define PSDBDRIVERINFO PSDBENTRYINFO; // // Query attribute APIs // PVOID SdbGetFileInfo( IN HSDB hSDB, IN LPCTSTR pwszFilePath, IN HANDLE hFile OPTIONAL, IN LPVOID pImageBase OPTIONAL, IN DWORD dwImageSize OPTIONAL, IN BOOL bNoCache ); VOID SdbFreeFileInfo( IN PVOID pFileInfo ); // // Get item from item ref // TAGREF SdbGetItemFromItemRef( IN HSDB hSDB, IN TAGREF trItemRef, IN TAG tagItemKey, IN TAG tagItemTAGID, IN TAG tagItem ); #define SdbGetShimFromShimRef(hSDB, trShimRef) \ (SdbGetItemFromItemRef(hSDB, trShimRef, TAG_NAME, TAG_SHIM_TAGID, TAG_SHIM)) #define SdbGetPatchFromPatchRef(hSDB, trPatchRef) \ (SdbGetItemFromItemRef(hSDB, trPatchRef, TAG_NAME, TAG_PATCH_TAGID, TAG_PATCH)) #define SdbGetFlagFromFlagRef(hSDB, trFlagRef) \ (SdbGetItemFromItemRef(hSDB, trFlagRef, TAG_NAME, TAG_FLAG_TAGID, TAG_FLAG)) // INDEX functions BOOL SdbDeclareIndex( IN PDB pdb, IN TAG tWhich, IN TAG tKey, IN DWORD dwEntries, IN BOOL bUniqueKey, OUT INDEXID* piiIndex ); BOOL SdbStartIndexing( IN PDB pdb, IN INDEXID iiWhich ); BOOL SdbStopIndexing( IN PDB pdb, IN INDEXID iiWhich ); BOOL SdbCommitIndexes( IN PDB pdb ); TAGID SdbFindFirstDWORDIndexedTag( IN PDB pdb, IN TAG tWhich, IN TAG tKey, IN DWORD dwName, OUT FIND_INFO* pFindInfo ); TAGID SdbFindNextDWORDIndexedTag( IN PDB pdb, OUT FIND_INFO* pFindInfo ); TAGID SdbFindFirstStringIndexedTag( IN PDB pdb, IN TAG tWhich, IN TAG tKey, IN LPCTSTR pwszName, OUT FIND_INFO* pFindInfo ); TAGID SdbFindNextStringIndexedTag( IN PDB pdb, OUT FIND_INFO* pFindInfo ); TAGID SdbFindFirstGUIDIndexedTag( IN PDB pdb, IN TAG tWhich, IN TAG tKey, IN GUID* pGuidName, OUT FIND_INFO* pFindInfo ); TAGID SdbFindNextGUIDIndexedTag( IN PDB pdb, OUT FIND_INFO* pFindInfo ); ULONGLONG SdbMakeIndexKeyFromString( IN LPCTSTR pwszKey ); // // These macros allow to make a key from dword or a guid // #define MAKEKEYFROMDWORD(dwValue) \ ((ULONGLONG)(dwValue)) #if defined(_WIN64) ULONGLONG SdbMakeIndexKeyFromGUID( IN GUID* pGuid ); #define MAKEKEYFROMGUID(pGuid) SdbMakeIndexKeyFromGUID(pGuid) #else /* ! WIN64 */ #define MAKEKEYFROMGUID(pGuid) \ ((ULONGLONG)((*(PULONGLONG)(pGuid)) ^ (*((PULONGLONG)(pGuid) + 1)))) #endif /* WIN64 */ TAGID SdbGetIndex( IN PDB pdb, IN TAG tWhich, IN TAG tKey, OUT LPDWORD lpdwFlags OPTIONAL ); #define SdbIsIndexAvailable(pdb, tWhich, tKey) \ (SdbGetIndex(pdb, tWhich, tKey, NULL)) // // WRITE FUNCTIONS // TAGID SdbBeginWriteListTag( IN PDB pdb, IN TAG tTag ); BOOL SdbEndWriteListTag( IN PDB pdb, IN TAGID tiList ); BOOL SdbWriteStringTagDirect( IN PDB pdb, IN TAG tTag, IN LPCWSTR pwszData ); BOOL SdbWriteStringRefTag( IN PDB pdb, IN TAG tTag, IN STRINGREF srData ); BOOL SdbWriteNULLTag( IN PDB pdb, IN TAG tTag ); BOOL SdbWriteBYTETag( IN PDB pdb, IN TAG tTag, IN BYTE jData ); BOOL SdbWriteWORDTag( IN PDB pdb, IN TAG tTag, IN WORD wData ); BOOL SdbWriteDWORDTag( IN PDB pdb, IN TAG tTag, IN DWORD dwData ); BOOL SdbWriteQWORDTag( IN PDB pdb, IN TAG tTag, IN ULONGLONG qwData ); BOOL SdbWriteStringTag( IN PDB pdb, IN TAG tTag, IN LPCWSTR pwszData ); BOOL SdbWriteBinaryTag( IN PDB pdb, IN TAG tTag, IN PBYTE pBuffer, IN DWORD dwSize ); BOOL SdbWriteBinaryTagFromFile( IN PDB pdb, IN TAG tTag, IN LPCWSTR pwszPath ); //////////////////////////////////////////////////////////////////////////////////////////// // // Attribute retrieval // // // // Attribute Information // identified by a tag // // typedef struct tagATTRINFO { TAG tAttrID; // tag for this attribute (includes type) DWORD dwFlags; // flags : such as "not avail" or "not there yet" union { // anonymous union with values ULONGLONG ullAttr; // QWORD value (TAG_TYPE_QWORD) DWORD dwAttr; // DWORD value (TAG_TYPE_DWORD) TCHAR* lpAttr; // WCHAR* value (TAG_TYPE_STRINGREF) }; } ATTRINFO, *PATTRINFO; // // Flags that go into ATTRINFO's dwFlags field // // #define ATTRIBUTE_AVAILABLE 0x00000001 // this will be set if attribute was obtained #define ATTRIBUTE_FAILED 0x00000002 // this will be set if we tried to get it // and failed BOOL SDBAPI SdbGetFileAttributes( IN LPCTSTR lpwszFileName, OUT PATTRINFO* ppAttrInfo, OUT LPDWORD lpdwAttrCount); BOOL SDBAPI SdbFreeFileAttributes( IN PATTRINFO pFileAttributes); BOOL SDBAPI SdbFormatAttribute( IN PATTRINFO pAttrInfo, OUT LPTSTR pchBuffer, IN DWORD dwBufferSize); //////////////////////////////////////////////////////////////////////////////////////////// // // // High-level functions to extract information related to apphelp // // typedef struct tagAPPHELP_DATA { DWORD dwFlags; // flags (if any) DWORD dwSeverity; // can be none APPTYPE_NONE (0) DWORD dwHTMLHelpID; // help id LPTSTR szAppName; TAGREF trExe; // matched on this exe (in apphelp section) LPTSTR szURL; // URL LPTSTR szLink; // link text LPTSTR szAppTitle; // title LPTSTR szContact; // contact info LPTSTR szDetails; // details // // non-apphelp data (this is managed by the host app // DWORD dwData; } APPHELP_DATA, *PAPPHELP_DATA; BOOL SdbReadApphelpData( IN HSDB hSDB, IN TAGREF trExe, OUT PAPPHELP_DATA pData ); BOOL SdbReadApphelpDetailsData( IN PDB pdbDetails, OUT PAPPHELP_DATA pData ); //////////////////////////////////////////////////////////////////////////////////////////// // // // A few functions from apphelp.dll // // BOOL SDBAPI SetPermLayers( IN LPCWSTR pwszPath, // path to the file to set a permanent layer on IN LPCWSTR pwszLayers, // layers to apply to the file, separated by spaces IN BOOL bMachine // TRUE if the layers should be persisted per machine ); BOOL SDBAPI GetPermLayers( IN LPCWSTR pwszPath, // path to the file to set a permanent layer on OUT LPWSTR pwszLayers, // layers to apply to the file, separated by spaces OUT DWORD* pdwBytes, // input: number of bytes available; output is number of bytes needed IN DWORD dwFlags ); BOOL SDBAPI AllowPermLayer( IN LPCWSTR pwszPath // path to the file to check whether you can set a permanent layer on ); typedef struct _NTVDM_FLAGS { DWORD dwWOWCompatFlags; DWORD dwWOWCompatFlagsEx; DWORD dwUserWOWCompatFlags; DWORD dwWOWCompatFlags2; DWORD dwWOWCompatFlagsFE; DWORD dwFlagsInfoSize; // size of the memory area pointed to by pFlagsInfo PVOID pFlagsInfo; // pointer that is used to store flags-related information } NTVDM_FLAGS, *PNTVDM_FLAGS; // // Macros we use to obtain flags command lines // #define MAKEQWORD(dwLow, dwHigh) \ ( ((ULONGLONG)(dwLow)) | ( ((ULONGLONG)(dwHigh)) << 32) ) #define GET_WOWCOMPATFLAGS_CMDLINE(pFlagInfo, dwFlag, ppCmdLine) \ SdbQueryFlagInfo(pFlagInfo, TAG_FLAGS_NTVDM1, MAKEQWORD(dwFlag, 0), ppCmdLine) #define GET_WOWCOMPATFLAGSEX_CMDLINE(pFlagInfo, dwFlag, ppCmdLine) \ SdbQueryFlagInfo(pFlagInfo, TAG_FLAGS_NTVDM1, MAKEQWORD(0, dwFlag), ppCmdLine) #define GET_USERWOWCOMPATFLAGS_CMDLINE(pFlagInfo, dwFlag, ppCmdLine) \ SdbQueryFlagInfo(pFlagInfo, TAG_FLAGS_NTVDM2, MAKEQWORD(dwFlag, 0), ppCmdLine) #define GET_WOWCOMPATFLAGS2_CMDLINE(pFlagInfo, dwFlag, ppCmdLine) \ SdbQueryFlagInfo(pFlagInfo, TAG_FLAGS_NTVDM2, MAKEQWORD(0, dwFlag), ppCmdLine) #define GET_WOWCOMPATFLAGSFE_CMDLINE(pFlagInfo, dwFlag, ppCmdLine) \ SdbQueryFlagInfo(pFlagInfo, TAG_FLAGS_NTVDM3, MAKEQWORD(dwFlag, 0), ppCmdLine) typedef struct _APPHELP_INFO { // // html help id mode // DWORD dwHtmlHelpID; // html help id DWORD dwSeverity; // must have LPCTSTR lpszAppName; GUID guidID; // entry guid // // Conventional mode // TAGID tiExe; // the TAGID of the exe entry within the DB GUID guidDB; // the guid of the DB that has the EXE entry BOOL bOfflineContent; BOOL bUseHTMLHelp; LPCTSTR lpszChmFile; LPCTSTR lpszDetailsFile; // // preserve users choice on the dialog if user chooses to persist settings // BOOL bPreserveChoice; // // TRUE if msi mode (matters for ia64 platform) // BOOL bMSI; } APPHELP_INFO, *PAPPHELP_INFO; //////////////////////////////////////////////////////////////////////////////////////////// // // // Functions to access apphelp functionality // // // prototypes which are exported for ntvdm shim support typedef void (*LPFNSE_REMOVENTVDM)(HANDLE); typedef BOOL (*LPFNSE_SHIMNTVDM)(LPCWSTR, HSDB, SDBQUERYRESULT*, PVDMTABLE); // Max size of compat layer buffer #define COMPATLAYERMAXLEN 256 BOOL ApphelpGetNTVDMInfo( IN LPCWSTR pwszPath, // path to the app in NT format IN LPCWSTR pwszModule, // module name IN LPCWSTR pEnvironment, // pointer to the environment of the task that is // being created or NULL if we are to use the main NTVDM // environment block. OUT LPWSTR pszCompatLayer, // The new compat layer variable. with format: // "Alpha Bravo Charlie" -- allow COMPATLAYERMAXLEN chars for this. OUT PNTVDM_FLAGS pFlags, // The flags OUT PAPPHELP_INFO pAHInfo, // If there is apphelp to display, this will be filled // in with non-null values OUT HSDB* phSDB, // The handle to the database. OUT PSDBQUERYRESULT pQueryResult // The query result. ); BOOL ApphelpShowDialog( IN PAPPHELP_INFO pAHInfo, // the info necessary to find the apphelp data IN PHANDLE phProcess // [optional] returns the process handle of // the process displaying the apphelp. // When the process completes, the return value // (from GetExitCodeProcess()) will be zero // if the app should not run, or non-zero // if it should run. ); typedef PVOID HAPPHELPINFOCONTEXT; typedef enum tagAPPHELPINFORMATIONCLASS { ApphelpFlags, ApphelpExeName, ApphelpAppName, ApphelpVendorName, ApphelpHtmlHelpID, ApphelpProblemSeverity, ApphelpLinkURL, ApphelpLinkText, ApphelpTitle, ApphelpDetails, ApphelpContact, ApphelpHelpCenterURL, ApphelpExeTagID, ApphelpDatabaseGUID // this is guid of a database containing the match } APPHELPINFORMATIONCLASS; PDB SDBAPI SdbOpenApphelpDetailsDatabase( IN LPCWSTR pwsDetailsDatabasePath OPTIONAL ); HAPPHELPINFOCONTEXT SDBAPI SdbOpenApphelpInformation( IN GUID* pguidDB, IN GUID* pguidID ); HAPPHELPINFOCONTEXT SDBAPI SdbOpenApphelpInformationByID( IN HSDB hSDB, IN TAGREF trEntry, IN DWORD dwDatabaseType // pass the type of db you are using ); BOOL SDBAPI SdbCloseApphelpInformation( IN HAPPHELPINFOCONTEXT hctx ); DWORD SDBAPI SdbQueryApphelpInformation( IN HAPPHELPINFOCONTEXT hctx, IN APPHELPINFORMATIONCLASS InfoClass, OUT LPVOID pBuffer, // may be NULL IN DWORD cbSize // may be 0 if pBuffer is NULL ); BOOL SDBAPI SdbQueryFlagMask( IN HSDB hSDB, IN SDBQUERYRESULT* pQueryResult, IN TAG tMaskType, OUT ULONGLONG* pullFlags, IN OUT PVOID* ppFlagInfo OPTIONAL ); BOOL SDBAPI SdbEscapeApphelpURL( OUT LPWSTR szResult, // escaped string (output) IN OUT LPDWORD pdwCount, // count of tchars in the buffer pointed to by szResult IN LPCWSTR szToEscape // string to escape ); BOOL SDBAPI SdbSetApphelpDebugParameters( IN HAPPHELPINFOCONTEXT hctx, IN LPCWSTR pszDetailsDatabase OPTIONAL, IN BOOL bOfflineContent OPTIONAL, // pass FALSE IN BOOL bUseHtmlHelp OPTIONAL, // pass FALSE IN LPCWSTR pszChmFile OPTIONAL // pass NULL ); BOOL SdbShowApphelpDialog( // returns TRUE if success, whether we should run the app is in pRunApp IN PAPPHELP_INFO pAHInfo, // the info necessary to find the apphelp data OUT PHANDLE phProcess, // [optional] returns the process handle of // the process displaying the apphelp. // When the process completes, the return value // (from GetExitCodeProcess()) will be zero // if the app should not run, or non-zero // if it should run. IN OUT BOOL* pRunApp ); // // WOW cmd line for flags interface // instead of calling SdbQueryFlagInfo the macros above should be used // BOOL SDBAPI SdbQueryFlagInfo( IN PVOID pvFlagInfo, IN TAG tFlagType, IN ULONGLONG ullFlagMask, OUT LPCTSTR * ppCmdLine ); BOOL SDBAPI SdbFreeFlagInfo( IN PVOID pvFlagInfo ); //////////////////////////////////////////////////////////////////////////////////////////// // // App Verifier macros/defs // // typedef enum _VLOG_LEVEL { VLOG_LEVEL_INFO, VLOG_LEVEL_WARNING, VLOG_LEVEL_ERROR } VLOG_LEVEL, *PVLOG_LEVEL; typedef enum _AVRF_INFO_ID { // INFO ID type actually being passed in PVOID param // ------- ----------------------------------------- AVRF_INFO_NUM_SHIMS, // LPDWORD (preallocated) (szName should be NULL) AVRF_INFO_SHIM_NAMES, // LPWSTR * (array of same size as value of AVRF_INFO_NUM_SHIMS) // (array is preallocated, strings are allocated by shim) // (szName should be NULL) AVRF_INFO_DESCRIPTION, // LPWSTR (allocated by shim) AVRF_INFO_FRIENDLY_NAME, // LPWSTR (allocated by shim) AVRF_INFO_INCLUDE_EXCLUDE, // LPWSTR (allocated by shim) AVRF_INFO_FLAGS, // LPDWORD (preallocated) AVRF_INFO_OPTIONS_PAGE, // LPPROPSHEETPAGE (preallocated) AVRF_INFO_VERSION, // LPDWORD (preallocated), HIWORD=major version, LOWORD=minor version AVRF_INFO_GROUPS // LPDWORD (preallocated) } AVRF_INFO_ID, *PAVRF_INFO_ID; // // FLAGS for verifier shims (all flags default to FALSE) // #define AVRF_FLAG_NO_DEFAULT 0x00000001 // this shim should not be turned on by default #define AVRF_FLAG_NO_WIN2K 0x00000002 // this shim should not be used on win2K #define AVRF_FLAG_NO_SHIM 0x00000004 // this "shim" is a placeholder and shouldn't actually // be applied to an app #define AVRF_FLAG_NO_TEST 0x00000008 // this "shim" is not a test, and is purely for adding // a page to the options dialog #define AVRF_FLAG_NOT_SETUP 0x00000010 // this shim is not appropriate for setup apps #define AVRF_FLAG_ONLY_SETUP 0x00000020 // this shim is only appropriate for setup apps #define AVRF_FLAG_RUN_ALONE 0x00000040 // this shim should be run by itself with no other shims applied #define AVRF_FLAG_INTERNAL_ONLY 0x00000080 // this shim is for Microsoft internal use only #define AVRF_FLAG_EXTERNAL_ONLY 0x00000100 // this shim if for external use only - not for MS users // // GROUPS for verifier shims (by default, shims are in no groups) // #define AVRF_GROUP_SETUP 0x00000001 // suitable for checking setup programs #define AVRF_GROUP_NON_SETUP 0x00000002 // suitable for checking non-setup programs (can be both) #define AVRF_GROUP_LOGO 0x00000004 // shims that are useful for logo testing // // magic number tells us if we're using the same shim interface // #define VERIFIER_SHIMS_MAGIC 'avfr' typedef DWORD (*_pfnGetVerifierMagic)(void); typedef BOOL (*_pfnQueryShimInfo)(LPCWSTR szName, AVRF_INFO_ID eInfo, PVOID pInfo); // // special callback, so a shim can be notified when it is activated or deactivated for a // specific application. // typedef BOOL (*_pfnActivateCallback)(LPCWSTR szAppName, BOOL bActivate); // // Where we store default verifier shim settings // #define AVRF_DEFAULT_SETTINGS_NAME TEXT("{default}") #define AVRF_DEFAULT_SETTINGS_NAME_W L"{default}" #define AVRF_DEFAULT_SETTINGS_NAME_A "{default}" typedef struct _SHIM_DESCRIPTION { LPWSTR szName; LPWSTR szDescription; LPWSTR szExcludes; // comma separated module names LPWSTR szIncludes; // comma separated module names DWORD dwFlags; } SHIM_DESCRIPTION, *PSHIM_DESCRIPTION; #define ENUM_SHIMS_MAGIC 'enum' typedef DWORD (*_pfnEnumShims)(PSHIM_DESCRIPTION pShims, DWORD dwMagic); typedef BOOL (*_pfnIsVerifierDLL)(void); //////////////////////////////////////////////////////////////////////////////////////////// // // Miscelaneous macros/defs // // // // Apphelp types // #define APPHELP_TYPE_MASK 0x000000FF #define APPHELP_NONE 0x00000000 #define APPHELP_NOBLOCK 0x00000001 #define APPHELP_HARDBLOCK 0x00000002 #define APPHELP_MINORPROBLEM 0x00000003 #define APPHELP_REINSTALL 0x00000004 #define APPHELP_VERSIONSUB 0x00000005 #define APPHELP_SHIM 0x00000006 // // Match modes for EXEs // #define MATCH_NORMAL 0 #define MATCH_EXCLUSIVE 1 #define MATCH_ADDITIVE 2 // // the struct below packs into a WORD // older compilers won't like this union // (because of nameless members) // // Tell compiler to be quite about the nameless member. #pragma warning (disable : 4201 ) typedef union tagMATCHMODE { struct { USHORT Type : 4; // type of match USHORT Flags: 4; // flags for matching // future expansion here }; WORD wMatchMode; // we use this to init from the database DWORD dwMatchMode; // this is the "whole" match mode } MATCHMODE, *PMATCHMODE; #pragma warning (default : 4201 ) // // match modes: // // normal -- find a match, we're done // additive -- keep the match, then keep matching according to flags // exclusive -- keep the match, throw away all other matches // static const MATCHMODE MatchModeDefaultMain = { { MATCH_NORMAL, 0 } }; #define MATCHMODE_DEFAULT_MAIN (MatchModeDefaultMain.wMatchMode) static const MATCHMODE MatchModeDefaultCustom = { { MATCH_ADDITIVE, 0 } }; #define MATCHMODE_DEFAULT_CUSTOM (MatchModeDefaultCustom.wMatchMode) #define MAKE_MATCHMODE(dwMatchMode, Type, Flags) \ { \ ((PMATCHMODE)&(dwMatchMode))->Type = Type; \ ((PMATCHMODE)&(dwMatchMode))->Flags = Flags; \ } // // Pre-defined match modes for shimdbc // static const MATCHMODE MatchModeNormal = { { MATCH_NORMAL, 0 } }; static const MATCHMODE MatchModeAdditive = { { MATCH_ADDITIVE, 0 } }; static const MATCHMODE MatchModeExclusive = { { MATCH_EXCLUSIVE, 0 } }; #define MATCHMODE_NORMAL_SHIMDBC (MatchModeNormal.wMatchMode) #define MATCHMODE_ADDITIVE_SHIMDBC (MatchModeAdditive.wMatchMode) #define MATCHMODE_EXCLUSIVE_SHIMDBC (MatchModeExclusive.wMatchMode) // // Layer flags // #define LAYER_FLAG_NONE 0x00000000 // None #define LAYER_APPLY_TO_SYSTEM_EXES 0x00000001 // Apply to exes in system32 (including sub dir) and windir #define LAYER_USE_NO_EXE_ENTRIES 0x00000002 // Do not use any EXE entries // // Runtime platform flags // #define RUNTIME_PLATFORM_FLAG_NOT 0x80000000 #define RUNTIME_PLATFORM_FLAG_NOT_ELEMENT 0x00000080 #define RUNTIME_PLATFORM_FLAG_VALID 0x00000040 #define RUNTIME_PLATFORM_MASK_ELEMENT 0x000000FF #define RUNTIME_PLATFORM_MASK_VALUE 0x0000003F #define RUNTIME_PLATFORM_ANY 0xC0000000 // no valid bits + NOT + flag // // Shimdbc compile-time platform (OS_PLATFORM) flags // #define OS_PLATFORM_NONE 0x00000000 #define OS_PLATFORM_I386 0x00000001 #define OS_PLATFORM_IA64 0x00000002 #define OS_PLATFORM_ALL 0xFFFFFFFF // // These definitions are used for OS SKU attribute tags on EXE entries // #define OS_SKU_NONE 0x00000000 // None #define OS_SKU_PER 0x00000001 // Personal #define OS_SKU_PRO 0x00000002 // Professional #define OS_SKU_SRV 0x00000004 // Server #define OS_SKU_ADS 0x00000008 // Advanced Server #define OS_SKU_DTC 0x00000010 // Datacenter #define OS_SKU_BLA 0x00000020 // Blade Server #define OS_SKU_TAB 0x00000040 // TabletPC #define OS_SKU_MED 0x00000080 // eHome #define OS_SKU_SBS 0x00000100 // Small business server #define OS_SKU_ALL 0xFFFFFFFF #ifndef ARRAYSIZE #define ARRAYSIZE(rg) (sizeof(rg)/sizeof((rg)[0])) #endif #ifndef OFFSETOF #define OFFSETOF offsetof #endif #define CHARCOUNT(sz) (sizeof(sz) / sizeof(sz[0])) // // our reg key locations // #define APPCOMPAT_LOCATION TEXT("Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags") #define APPCOMPAT_KEY_PATH APPCOMPAT_LOCATION #define APPCOMPAT_KEY_PATH_CUSTOM APPCOMPAT_LOCATION TEXT("\\Custom") #define APPCOMPAT_KEY_PATH_INSTALLEDSDB APPCOMPAT_LOCATION TEXT("\\InstalledSDB") #define POLICY_KEY_APPCOMPAT TEXT("Software\\Policies\\Microsoft\\Windows\\AppCompat") #define POLICY_VALUE_DISABLE_ENGINE TEXT("DisableEngine") #define POLICY_VALUE_DISABLE_WIZARD TEXT("DisableWizard") #define POLICY_VALUE_DISABLE_PROPPAGE TEXT("DisablePropPage") #define POLICY_VALUE_APPHELP_LOG TEXT("LogAppHelpEvents") // NT API versions #define APPCOMPAT_KEY_PATH_MACHINE TEXT("\\Registry\\Machine\\") APPCOMPAT_LOCATION #define APPCOMPAT_KEY_PATH_NT TEXT("\\") APPCOMPAT_LOCATION #define APPCOMPAT_PERM_LAYER_PATH TEXT("\\") APPCOMPAT_LOCATION TEXT("\\Layers") #define APPCOMPAT_KEY_PATH_MACHINE_CUSTOM APPCOMPAT_KEY_PATH_MACHINE TEXT("\\Custom") #define APPCOMPAT_KEY_PATH_MACHINE_INSTALLEDSDB APPCOMPAT_KEY_PATH_MACHINE TEXT("\\InstalledSDB") // // our reg key locations // #define POLICY_VALUE_APPHELP_LOG_A "LogAppHelpEvents" // // our reg key locations // #define APPCOMPAT_LOCATION_W L"Software\\Microsoft\\Windows NT\\CurrentVersion\\AppCompatFlags" #define APPCOMPAT_KEY_PATH_W APPCOMPAT_LOCATION_W #define APPCOMPAT_KEY_PATH_CUSTOM_W APPCOMPAT_LOCATION_W L"\\Custom" #define APPCOMPAT_KEY_PATH_INSTALLEDSDB_W APPCOMPAT_LOCATION_W L"\\InstalledSDB" #define POLICY_KEY_APPCOMPAT_W L"Software\\Policies\\Microsoft\\Windows\\AppCompat" #define POLICY_VALUE_DISABLE_ENGINE_W L"DisableEngine" #define POLICY_VALUE_DISABLE_WIZARD_W L"DisableWizard" #define POLICY_VALUE_DISABLE_PROPPAGE_W L"DisablePropPage" #define POLICY_VALUE_APPHELP_LOG_W L"LogAppHelpEvents" // // LUA all-users redirection location // #define LUA_REDIR ("%ALLUSERSPROFILE%\\Application Data\\Redirected") #define LUA_REDIR_W TEXT("%ALLUSERSPROFILE%\\Application Data\\Redirected") // // debug output support // typedef enum tagSHIMDBGLEVEL { sdlError = 1, sdlWarning = 2, sdlFail = 1, // this means we have failed some api, not necessarily fatal sdlInfo = 3, sdlUser = 4 } SHIMDBGLEVEL; typedef enum _SHIMVIEWER_OPTION { SHIMVIEWER_OPTION_UNINITIAZED, SHIMVIEWER_OPTION_NO, SHIMVIEWER_OPTION_YES } SHIMVIEWER_OPTION; // // This flag marks the debug out for shimviewer // #define sdlLogShimViewer 0x00000080UL #define sdlMask 0x0000007FUL #define SHIMVIEWER_DATA_SIZE 1024 #define SHIMVIEWER_DATA_PREFIX L"SHIMVIEW:" #define SHIMVIEWER_DATA_PREFIX_LEN (sizeof(SHIMVIEWER_DATA_PREFIX)/sizeof(WCHAR) - 1) #define FILTER_DBG_LEVEL(level) ((int)((level) & sdlMask)) extern int __cdecl ShimDbgPrint(INT iDebugLevel, PCH FunctionName, PCH Format, ...); #if DBG // Define _DEBUG_SPEW when compiling checked #ifndef _DEBUG_SPEW #define _DEBUG_SPEW #endif #endif // DBG #ifdef _DEBUG_SPEW // // This value is a large number (initiallly) // We will initialize it from the environment upon the first call // to ShimDbgPrint // extern int g_iShimDebugLevel; #define DBGPRINT( _x_ ) \ { \ if (g_iShimDebugLevel) { \ ShimDbgPrint _x_; \ } \ } #else #define DBGPRINT(_x_) #endif // _DEBUG_SPEW // // This is an option controlled by the ShowDebugInfo value under // HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags. // #define APPCOMPAT_KEY_PATH_W_WITH_SLASH L"\\" APPCOMPAT_LOCATION_W #define SHIMENG_SHOW_DEBUG_INFO L"ShowDebugInfo" extern SHIMVIEWER_OPTION g_eShimViewerOption; SHIMVIEWER_OPTION SdbGetShowDebugInfoOption( void ); /////////////////////////////////////////////////////////////////////////////// // // SHIM TAGS // // // Function to get the tag names given a tag ID. // // WARNING !!! : If you add new tags make sure you update SdbApi\attributes.c // with the name of the tag in the global gaTagInfo. // LPCTSTR SDBAPI SdbTagToString( TAG tag ); // // LIST types for shimdb // #define TAG_DATABASE (0x1 | TAG_TYPE_LIST) #define TAG_LIBRARY (0x2 | TAG_TYPE_LIST) #define TAG_INEXCLUDE (0x3 | TAG_TYPE_LIST) #define TAG_SHIM (0x4 | TAG_TYPE_LIST) #define TAG_PATCH (0x5 | TAG_TYPE_LIST) #define TAG_APP (0x6 | TAG_TYPE_LIST) #define TAG_EXE (0x7 | TAG_TYPE_LIST) #define TAG_MATCHING_FILE (0x8 | TAG_TYPE_LIST) #define TAG_SHIM_REF (0x9 | TAG_TYPE_LIST) #define TAG_PATCH_REF (0xA | TAG_TYPE_LIST) #define TAG_LAYER (0xB | TAG_TYPE_LIST) #define TAG_FILE (0xC | TAG_TYPE_LIST) #define TAG_APPHELP (0xD | TAG_TYPE_LIST) #define TAG_LINK (0xE | TAG_TYPE_LIST) // Description list w/lang ids and urls #define TAG_DATA (0xF | TAG_TYPE_LIST) #define TAG_MSI_TRANSFORM (0x10| TAG_TYPE_LIST) #define TAG_MSI_TRANSFORM_REF (0x11| TAG_TYPE_LIST) #define TAG_MSI_PACKAGE (0x12| TAG_TYPE_LIST) #define TAG_FLAG (0x13| TAG_TYPE_LIST) #define TAG_MSI_CUSTOM_ACTION (0x14| TAG_TYPE_LIST) #define TAG_FLAG_REF (0x15| TAG_TYPE_LIST) #define TAG_ACTION (0x16| TAG_TYPE_LIST) // // STRINGREF types for shimdb // #define TAG_NAME (0x1 | TAG_TYPE_STRINGREF) #define TAG_DESCRIPTION (0x2 | TAG_TYPE_STRINGREF) #define TAG_MODULE (0x3 | TAG_TYPE_STRINGREF) #define TAG_API (0x4 | TAG_TYPE_STRINGREF) #define TAG_VENDOR (0x5 | TAG_TYPE_STRINGREF) #define TAG_APP_NAME (0x6 | TAG_TYPE_STRINGREF) #define TAG_COMMAND_LINE (0x8 | TAG_TYPE_STRINGREF) #define TAG_COMPANY_NAME (0x9 | TAG_TYPE_STRINGREF) #define TAG_DLLFILE (0xA | TAG_TYPE_STRINGREF) #define TAG_WILDCARD_NAME (0xB | TAG_TYPE_STRINGREF) #define TAG_PRODUCT_NAME (0x10 | TAG_TYPE_STRINGREF) #define TAG_PRODUCT_VERSION (0x11 | TAG_TYPE_STRINGREF) #define TAG_FILE_DESCRIPTION (0x12 | TAG_TYPE_STRINGREF) #define TAG_FILE_VERSION (0x13 | TAG_TYPE_STRINGREF) #define TAG_ORIGINAL_FILENAME (0x14 | TAG_TYPE_STRINGREF) #define TAG_INTERNAL_NAME (0x15 | TAG_TYPE_STRINGREF) #define TAG_LEGAL_COPYRIGHT (0x16 | TAG_TYPE_STRINGREF) #define TAG_16BIT_DESCRIPTION (0x17 | TAG_TYPE_STRINGREF) #define TAG_APPHELP_DETAILS (0x18 | TAG_TYPE_STRINGREF) // Details in single language #define TAG_LINK_URL (0x19 | TAG_TYPE_STRINGREF) #define TAG_LINK_TEXT (0x1A | TAG_TYPE_STRINGREF) #define TAG_APPHELP_TITLE (0x1B | TAG_TYPE_STRINGREF) #define TAG_APPHELP_CONTACT (0x1C | TAG_TYPE_STRINGREF) #define TAG_SXS_MANIFEST (0x1D | TAG_TYPE_STRINGREF) #define TAG_DATA_STRING (0x1E | TAG_TYPE_STRINGREF) #define TAG_MSI_TRANSFORM_FILE (0x1F | TAG_TYPE_STRINGREF) #define TAG_16BIT_MODULE_NAME (0x20 | TAG_TYPE_STRINGREF) #define TAG_LAYER_DISPLAYNAME (0x21 | TAG_TYPE_STRINGREF) #define TAG_COMPILER_VERSION (0x22 | TAG_TYPE_STRINGREF) #define TAG_ACTION_TYPE (0x23 | TAG_TYPE_STRINGREF) #define TAG_STRINGTABLE (0x801 | TAG_TYPE_LIST) // // DWORD types for shimdb // #define TAG_SIZE (0x1 | TAG_TYPE_DWORD) #define TAG_OFFSET (0x2 | TAG_TYPE_DWORD) #define TAG_CHECKSUM (0x3 | TAG_TYPE_DWORD) #define TAG_SHIM_TAGID (0x4 | TAG_TYPE_DWORD) #define TAG_PATCH_TAGID (0x5 | TAG_TYPE_DWORD) #define TAG_MODULE_TYPE (0x6 | TAG_TYPE_DWORD) #define TAG_VERDATEHI (0x7 | TAG_TYPE_DWORD) #define TAG_VERDATELO (0x8 | TAG_TYPE_DWORD) #define TAG_VERFILEOS (0x9 | TAG_TYPE_DWORD) #define TAG_VERFILETYPE (0xA | TAG_TYPE_DWORD) #define TAG_PE_CHECKSUM (0xB | TAG_TYPE_DWORD) #define TAG_PREVOSMAJORVER (0xC | TAG_TYPE_DWORD) #define TAG_PREVOSMINORVER (0xD | TAG_TYPE_DWORD) #define TAG_PREVOSPLATFORMID (0xE | TAG_TYPE_DWORD) #define TAG_PREVOSBUILDNO (0xF | TAG_TYPE_DWORD) #define TAG_PROBLEMSEVERITY (0x10 | TAG_TYPE_DWORD) #define TAG_LANGID (0x11 | TAG_TYPE_DWORD) #define TAG_VER_LANGUAGE (0x12 | TAG_TYPE_DWORD) #define TAG_ENGINE (0x14 | TAG_TYPE_DWORD) #define TAG_HTMLHELPID (0x15 | TAG_TYPE_DWORD) #define TAG_INDEX_FLAGS (0x16 | TAG_TYPE_DWORD) #define TAG_FLAGS (0x17 | TAG_TYPE_DWORD) #define TAG_DATA_VALUETYPE (0x18 | TAG_TYPE_DWORD) #define TAG_DATA_DWORD (0x19 | TAG_TYPE_DWORD) #define TAG_LAYER_TAGID (0x1A | TAG_TYPE_DWORD) #define TAG_MSI_TRANSFORM_TAGID (0x1B | TAG_TYPE_DWORD) #define TAG_LINKER_VERSION (0x1C | TAG_TYPE_DWORD) #define TAG_LINK_DATE (0x1D | TAG_TYPE_DWORD) #define TAG_UPTO_LINK_DATE (0x1E | TAG_TYPE_DWORD) #define TAG_OS_SERVICE_PACK (0x1F | TAG_TYPE_DWORD) #define TAG_FLAG_TAGID (0x20 | TAG_TYPE_DWORD) #define TAG_RUNTIME_PLATFORM (0x21 | TAG_TYPE_DWORD) #define TAG_OS_SKU (0x22 | TAG_TYPE_DWORD) #define TAG_TAGID (0x801| TAG_TYPE_DWORD) // // STRING types // #define TAG_STRINGTABLE_ITEM (0x801 | TAG_TYPE_STRING) // // NULL types for shimdb (existence/nonexistence is treated like a BOOL) // #define TAG_INCLUDE (0x1 | TAG_TYPE_NULL) #define TAG_GENERAL (0x2 | TAG_TYPE_NULL) #define TAG_MATCH_LOGIC_NOT (0x3 | TAG_TYPE_NULL) #define TAG_APPLY_ALL_SHIMS (0x4 | TAG_TYPE_NULL) #define TAG_USE_SERVICE_PACK_FILES (0x5 | TAG_TYPE_NULL) // // QWORD types for shimdb // #define TAG_TIME (0x1 | TAG_TYPE_QWORD) #define TAG_BIN_FILE_VERSION (0x2 | TAG_TYPE_QWORD) #define TAG_BIN_PRODUCT_VERSION (0x3 | TAG_TYPE_QWORD) #define TAG_MODTIME (0x4 | TAG_TYPE_QWORD) #define TAG_FLAG_MASK_KERNEL (0x5 | TAG_TYPE_QWORD) #define TAG_UPTO_BIN_PRODUCT_VERSION (0x6 | TAG_TYPE_QWORD) #define TAG_DATA_QWORD (0x7 | TAG_TYPE_QWORD) #define TAG_FLAG_MASK_USER (0x8 | TAG_TYPE_QWORD) #define TAG_FLAGS_NTVDM1 (0x9 | TAG_TYPE_QWORD) #define TAG_FLAGS_NTVDM2 (0xA | TAG_TYPE_QWORD) #define TAG_FLAGS_NTVDM3 (0xB | TAG_TYPE_QWORD) #define TAG_FLAG_MASK_SHELL (0xC | TAG_TYPE_QWORD) #define TAG_UPTO_BIN_FILE_VERSION (0xD | TAG_TYPE_QWORD) #define TAG_FLAG_MASK_FUSION (0xE | TAG_TYPE_QWORD) // // BINARY types for shimdb // #define TAG_PATCH_BITS (0x2 | TAG_TYPE_BINARY) #define TAG_FILE_BITS (0x3 | TAG_TYPE_BINARY) #define TAG_EXE_ID (0x4 | TAG_TYPE_BINARY) #define TAG_DATA_BITS (0x5 | TAG_TYPE_BINARY) #define TAG_MSI_PACKAGE_ID (0x6 | TAG_TYPE_BINARY) // msi package id is a guid #define TAG_DATABASE_ID (0x7 | TAG_TYPE_BINARY) // database guid #define TAG_INDEX_BITS (0x801 | TAG_TYPE_BINARY) // // INDEX types for shimdb // #define TAG_INDEXES (0x802 | TAG_TYPE_LIST) #define TAG_INDEX (0x803 | TAG_TYPE_LIST) // // WORD types // #define TAG_MATCH_MODE (0x1 | TAG_TYPE_WORD) #define TAG_TAG (0x801 | TAG_TYPE_WORD) #define TAG_INDEX_TAG (0x802 | TAG_TYPE_WORD) #define TAG_INDEX_KEY (0x803 | TAG_TYPE_WORD) // // let the typedefs take the course.. // #undef LPCTSTR #undef LPTSTR #undef TCHAR #endif // _SHIMDB_H_
26.747261
116
0.621654
[ "transform" ]
c0d2fecf11ed9fc8d1f4de043b511114ebcabebe
962
h
C
Webserver/Net/Http/V2/Frame.h
ChristopherHX/mcpelauncher-updates
5654973d8c2c36859566cbcaf0dfd314e6d7df29
[ "MIT" ]
3
2021-10-31T12:24:24.000Z
2022-02-15T18:16:05.000Z
Webserver/Net/Http/V2/Frame.h
ChristopherHX/mcpelauncher-updates
5654973d8c2c36859566cbcaf0dfd314e6d7df29
[ "MIT" ]
2
2021-12-10T06:16:16.000Z
2021-12-24T12:21:01.000Z
Webserver/Net/Http/V2/Frame.h
minecraft-linux/mcpelauncher-updates
e85c26a9c7c02778bba4535109b41d4a9349b623
[ "MIT" ]
2
2021-12-08T10:15:12.000Z
2021-12-11T18:25:40.000Z
#pragma once #include <cstdint> #include <vector> #include "Stream.h" void AddUInt31(uint32_t number, std::vector<uint8_t>::iterator & destination); void AddUInt32(uint32_t number, std::vector<uint8_t>::iterator & destination); namespace Net { namespace Http { namespace V2 { struct Frame { public: enum class Type : uint8_t { DATA = 0x0, HEADERS = 0x1, PRIORITY = 0x2, RST_STREAM = 0x3, SETTINGS = 0x4, PUSH_PROMISE = 0x5, PING = 0x6, GOAWAY = 0x7, WINDOW_UPDATE = 0x8, CONTINUATION = 0x9 }; enum class Flag : uint8_t { END_STREAM = 0x1, ACK = 0x1, END_HEADERS = 0x4, PADDED = 0x8, PRIORITY = 0x20 }; uint32_t length; Type type; Flag flags; std::shared_ptr<Stream> stream; Frame(); bool HasFlag(Flag flag) const; std::vector<uint8_t> ToArray() const; }; } } }
18.862745
79
0.570686
[ "vector" ]
c0eb6d86f0c17129b1ef95a0bf730604b1a87baf
36,271
c
C
nm/mgr/mgr_db.c
amontilla24/AndroidFixMe
0e4c7599beaf87e62be441fd30ba6b57500ca1b0
[ "Unlicense" ]
2
2018-10-20T12:41:45.000Z
2018-10-20T14:48:21.000Z
nm/mgr/mgr_db.c
amontilla24/AndroidFixMe
0e4c7599beaf87e62be441fd30ba6b57500ca1b0
[ "Unlicense" ]
null
null
null
nm/mgr/mgr_db.c
amontilla24/AndroidFixMe
0e4c7599beaf87e62be441fd30ba6b57500ca1b0
[ "Unlicense" ]
2
2018-10-20T14:16:39.000Z
2020-10-21T16:27:52.000Z
/***************************************************************************** ** ** File Name: mgr_db.h ** ** Description: This module captures the functions, structures, and operations ** necessary to store and retrieve user-defined content from the ** management daemon on system startup. ** ** Notes: ** ** Assumptions: ** ** ** Modification History: ** MM/DD/YY AUTHOR DESCRIPTION ** -------- ------------ --------------------------------------------- ** 07/18/15 E. Birrane Initial Implementation from mgr_db.[c|h] (Secure DTN - NASA: NNX14CS58P) *****************************************************************************/ // System headers. #include "unistd.h" // ION headers. #include "platform.h" #include "lyst.h" // Application headers. #include "../shared/adm/adm.h" #include "../shared/utils/db.h" #include "mgr_db.h" #include "../shared/primitives/var.h" #include "../shared/adm/adm_bp.h" #include "../shared/adm/adm_agent.h" #include "../shared/primitives/ctrl.h" #include "../shared/primitives/report.h" int mgr_db_compdata_forget(mid_t *mid) { var_t *item = mgr_vdb_compdata_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_compdata_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.compdata, item->desc.itemObj, item->desc.descObj); } int mgr_db_compdata_persist(var_t *item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.itemObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.itemObj == 0))) { AMP_DEBUG_ERR("mgr_db_compdata_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t *data = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ if((data = var_serialize(item, &(item->desc.size))) == NULL) { AMP_DEBUG_ERR("mgr_db_compdata_persist", "Unable to serialize new item.", NULL); return -1; } result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(var_desc_t), &(item->desc.descObj), gMgrDB.compdata); SRELEASE(data); if(result != 1) { AMP_DEBUG_ERR("mgr_db_compdata_persist","Unable to persist def.",NULL); return -1; } } else { var_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, sizeof(var_desc_t)); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(var_desc_t)); sdr_end_xn(sdr); } return 1; } int mgr_db_ctrl_forget(mid_t *mid) { ctrl_exec_t *item = mgr_vdb_ctrl_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_ctrl_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.ctrls, item->desc.itemObj, item->desc.descObj); } /****************************************************************************** * * \par Function Name: mgr_db_ctrl_persist * * \par Persist a control to the mgr SDR database. * * \param[in] item The control to persist. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ int mgr_db_ctrl_persist(ctrl_exec_t* item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.descObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.descObj == 0))) { AMP_DEBUG_ERR("mgr_db_ctrl_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t *data = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ if((data = ctrl_serialize(item, &(item->desc.size))) == NULL) { AMP_DEBUG_ERR("mgr_db_ctrl_persist", "Unable to serialize new ctrl.", NULL); return -1; } result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(ctrl_exec_desc_t), &(item->desc.descObj), gMgrDB.ctrls); SRELEASE(data); if(result != 1) { AMP_DEBUG_ERR("mgr_db_ctrl_persist","Unable to persist def.",NULL); return -1; } AMP_DEBUG_INFO("mgr_db_ctrl_persist","Persisted new ctrl", NULL); } else { ctrl_exec_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, sizeof(ctrl_exec_desc_t)); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(ctrl_exec_desc_t)); AMP_DEBUG_INFO("mgr_db_ctrl_persist","Updated ctrl", NULL); sdr_end_xn(sdr); } return 1; } int mgr_db_defgen_persist(Object db, def_gen_t* item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.itemObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.itemObj == 0))) { AMP_DEBUG_ERR("mgr_db_defgen_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t *data = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ if((data = def_serialize_gen(item, &(item->desc.size))) == NULL) { AMP_DEBUG_ERR("mgr_db_defgen_persist", "Unable to serialize new item.", NULL); return -1; } result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(def_gen_desc_t), &(item->desc.descObj), db); SRELEASE(data); if(result != 1) { AMP_DEBUG_ERR("mgr_db_defgen_persist","Unable to persist def.",NULL); return -1; } } else { def_gen_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, sizeof(def_gen_desc_t)); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(def_gen_desc_t)); sdr_end_xn(sdr); } return 1; } int mgr_db_forget(Object db, Object itemObj, Object descObj) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if(((itemObj == 0) && (descObj != 0)) || ((itemObj != 0) && (descObj == 0))) { AMP_DEBUG_ERR("mgr_db_Forget","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(itemObj != 0) { int result = db_forget(&(itemObj), &(descObj), db); if(result != 1) { AMP_DEBUG_ERR("mgr_db_forget","Unable to forget def.",NULL); return -1; } } return 1; } /****************************************************************************** * * \par Function Name: mgr_db_init * * \par Initialize items from the mgr SDR database. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. * 08/29/15 E. Birrane Updated to include SQL Account Information *****************************************************************************/ int mgr_db_init() { Sdr sdr; sdr = getIonsdr(); // * Initialize the non-volatile database. * / memset((char*) &gMgrDB, 0, sizeof(MgrDB)); /* Recover the Mgr database, creating it if necessary. */ CHKERR(sdr_begin_xn(sdr)); gMgrDB.descObj = sdr_find(sdr, "mgrdb", NULL); switch(gMgrDB.descObj) { case -1: // SDR error. * / sdr_cancel_xn(sdr); AMP_DEBUG_ERR("mgr_db_init", "Can't search for Mgr DB in SDR.", NULL); return -1; case 0: // Not found; Must create new DB. * / gMgrDB.descObj = sdr_malloc(sdr, sizeof(MgrDB)); if(gMgrDB.descObj == 0) { sdr_cancel_xn(sdr); AMP_DEBUG_ERR("mgr_db_init", "No space for mgr database.", NULL); return -1; } AMP_DEBUG_ALWAYS("mgr_db_init", "Creating DB", NULL); gMgrDB.compdata = sdr_list_create(sdr); gMgrDB.ctrls = sdr_list_create(sdr); gMgrDB.macros = sdr_list_create(sdr); gMgrDB.reports = sdr_list_create(sdr); gMgrDB.trls = sdr_list_create(sdr); gMgrDB.srls = sdr_list_create(sdr); #ifdef HAVE_MYSQL gMgrDB.sqldb = sdr_list_create(sdr); #endif sdr_write(sdr, gMgrDB.descObj, (char *) &gMgrDB, sizeof(MgrDB)); sdr_catlg(sdr, "mgrdb", 0, gMgrDB.descObj); break; default: /* Found DB in the SDR */ /* Read in the Database. */ sdr_read(sdr, (char *) &gMgrDB, gMgrDB.descObj, sizeof(MgrDB)); AMP_DEBUG_ALWAYS("mgr_db_init", "Found DB", NULL); } if(sdr_end_xn(sdr)) { AMP_DEBUG_ERR("mgr_db_init", "Can't create Mgr database.", NULL); return -1; } return 1; } int mgr_db_macro_forget(mid_t *mid) { def_gen_t *item = mgr_vdb_macro_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_macro_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.macros, item->desc.itemObj, item->desc.descObj); } int mgr_db_macro_persist(def_gen_t* ctrl) { return mgr_db_defgen_persist(gMgrDB.macros, ctrl); } int mgr_db_report_forget(mid_t *mid) { def_gen_t *item = mgr_vdb_report_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_report_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.reports, item->desc.itemObj, item->desc.descObj); } /****************************************************************************** * * \par Function Name: mgr_db_report_persist * * \par Persist a custom report definition to the mgr SDR database. * * \param[in] item The definition to persist. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ int mgr_db_report_persist(def_gen_t* item) { return mgr_db_defgen_persist(gMgrDB.reports, item); } int mgr_db_srl_forget(mid_t *mid) { srl_t *item = mgr_vdb_srl_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_srl_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.srls, item->desc.itemObj, item->desc.descObj); } /****************************************************************************** * * \par Function Name: mgr_db_srl_persist * * \par Persist a state-based rule to the mgr SDR database. * * \param[in] item The rule to persist. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/26/15 E. Birrane Initial implementation. *****************************************************************************/ int mgr_db_srl_persist(srl_t *item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.itemObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.itemObj == 0))) { AMP_DEBUG_ERR("mgr_db_srl_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t *data = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ if((data = srl_serialize(item, &(item->desc.size))) == NULL) { AMP_DEBUG_ERR("mgr_db_srl_persist", "Unable to serialize new item.", NULL); return -1; } result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(srl_desc_t), &(item->desc.descObj), gMgrDB.srls); SRELEASE(data); if(result != 1) { AMP_DEBUG_ERR("mgr_db_srl_persist","Unable to persist def.",NULL); return -1; } } else { srl_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, 0); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(srl_desc_t)); if(sdr_end_xn(sdr)) { AMP_DEBUG_ERR("mgr_db_srl_persist", "Can't create Mgr database.", NULL); return -1; } } return 1; } int mgr_db_trl_forget(mid_t *mid) { trl_t *item = mgr_vdb_trl_find(mid); if(item == NULL) { AMP_DEBUG_ERR("mgr_db_trl_forget","bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.trls, item->desc.itemObj, item->desc.descObj); } /****************************************************************************** * * \par Function Name: mgr_db_trl_persist * * \par Persist a time-based rule to the mgr SDR database. * * \param[in] item The rule to persist. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. * 06/26/15 E. Birrane Updated to new TRL structure/def. *****************************************************************************/ int mgr_db_trl_persist(trl_t *item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.itemObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.itemObj == 0))) { AMP_DEBUG_ERR("mgr_db_trl_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t *data = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ if((data = trl_serialize(item, &(item->desc.size))) == NULL) { AMP_DEBUG_ERR("mgr_db_trl_persist", "Unable to serialize new item.", NULL); return -1; } result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(trl_desc_t), &(item->desc.descObj), gMgrDB.trls); SRELEASE(data); if(result != 1) { AMP_DEBUG_ERR("mgr_db_trl_persist","Unable to persist def.",NULL); return -1; } } else { trl_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, 0); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(trl_desc_t)); if(sdr_end_xn(sdr)) { AMP_DEBUG_ERR("mgr_db_trl_persist", "Can't create Mgr database.", NULL); return -1; } } return 1; } #ifdef HAVE_MYSQL /****************************************************************************** * * \par Function Name: mgr_db_sql_forget * * \par Remove SQL DB information from the MGR SDR database. * * \param[in] item The sql account information. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 08/29/15 E. Birrane Initial implementation. *****************************************************************************/ int mgr_db_sql_forget(ui_db_t* item) { if(item == NULL) { AMP_DEBUG_ERR("mgr_db_sql_forget","Bad params.",NULL); return -1; } return mgr_db_forget(gMgrDB.sqldb, item->desc.itemObj, item->desc.descObj); } /****************************************************************************** * * \par Function Name: mgr_db_sql_persist * * \par Persist SQL account information to the mgr SDR database. * * \param[in] item The SQL account information to persist. * * \par Notes: * * \return 1 - Success * -1 - Failure * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 08/29/15 E. Birrane Initial implementation. *****************************************************************************/ int mgr_db_sql_persist(ui_db_t* item) { Sdr sdr = getIonsdr(); /* Step 0: Sanity Checks. */ if((item == NULL) || ((item->desc.itemObj == 0) && (item->desc.itemObj != 0)) || ((item->desc.itemObj != 0) && (item->desc.itemObj == 0))) { AMP_DEBUG_ERR("mgr_db_sql_persist","bad params.",NULL); return -1; } /* * Step 1: Determine if this is already in the SDR. We will assume * it is in the SDR already if its Object fields are nonzero. */ if(item->desc.itemObj == 0) { uint8_t data[UI_SQL_TOTLEN]; uint8_t *cursor = NULL; int result = 0; /* Step 1.1: Serialize the item to go into the SDR.. */ item->desc.size = UI_SQL_TOTLEN; cursor = &(data[0]); memcpy(cursor, item->database,UI_SQL_DBLEN); cursor += UI_SQL_DBLEN; memcpy(cursor, item->username,UI_SQL_ACCTLEN); cursor += UI_SQL_ACCTLEN; memcpy(cursor, item->password,UI_SQL_ACCTLEN); cursor += UI_SQL_ACCTLEN; memcpy(cursor, item->server,UI_SQL_SERVERLEN); cursor += UI_SQL_ACCTLEN; result = db_persist(data, item->desc.size, &(item->desc.itemObj), &(item->desc), sizeof(def_gen_desc_t), &(item->desc.descObj), gMgrDB.sqldb); if(result != 1) { AMP_DEBUG_ERR("mgr_db_sql_persist","Unable to persist SQL account information.",NULL); return -1; } } else { def_gen_desc_t temp; CHKERR(sdr_begin_xn(sdr)); sdr_stage(sdr, (char*) &temp, item->desc.descObj, 0); temp = item->desc; sdr_write(sdr, item->desc.descObj, (char *) &temp, sizeof(def_gen_desc_t)); if(sdr_end_xn(sdr)) { AMP_DEBUG_ERR("mgr_db_sql_persist", "Can't create SQL account info in the database.", NULL); return -1; } } return 1; } #endif /****************************************************************************** * * \par Function Name: mgr_vdb_add * * \par Add an item to a mutex-locked list. * * \param[in] item The item to add * \param[in] list The list to hold the item. * \param[in] mutex The mute protecting the list. * * \par Notes: * - This is a helper function used to add items to various mgr * lists. * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ void mgr_vdb_add(void *item, Lyst list, ResourceLock *mutex) { lockResource(mutex); lyst_insert_last(list, item); unlockResource(mutex); } void mgr_vdb_compdata_init(Sdr sdr) { uint32_t num = 0; num = mgr_vdb_defgen_init(sdr, gMgrDB.compdata, gMgrVDB.compdata, &(gMgrVDB.compdata_mutex)); AMP_DEBUG_ALWAYS("", "Added %d Computed Data Definitions from DB.", num); } var_t *mgr_vdb_compdata_find(mid_t *mid) { LystElt elt; var_t *cur = NULL; lockResource(&(gMgrVDB.compdata_mutex)); for(elt = lyst_first(gMgrVDB.compdata); elt; elt = lyst_next(elt)) { cur = (var_t *) lyst_data(elt); if(mid_compare(cur->id, mid, 1) == 0) { break; } cur = NULL; } unlockResource(&(gMgrVDB.compdata_mutex)); return cur; } void mgr_vdb_compdata_forget(mid_t *id) { LystElt elt; var_t *cur = NULL; lockResource(&(gMgrVDB.compdata_mutex)); for(elt = lyst_first(gMgrVDB.compdata); elt; elt = lyst_next(elt)) { cur = (var_t *) lyst_data(elt); if(mid_compare(cur->id, id, 1) == 0) { var_release(cur); lyst_delete(elt); break; } } unlockResource(&(gMgrVDB.compdata_mutex)); } /****************************************************************************** * * \par Function Name: mgr_vdb_ctrls_init * * \par Read controls from the SDR database into memory lists. * * \param[in] sdr The SDR containing the controls information. * * \par Notes: * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ void mgr_vdb_ctrls_init(Sdr sdr) { Object elt; Object descObj; ctrl_exec_desc_t cur_desc; ctrl_exec_t *cur_item; uint8_t *data = NULL; uint32_t bytes_used = 0; int num = 0; CHKVOID(sdr_begin_xn(sdr)); /* Step 1: Read through SDR list.... */ for (elt = sdr_list_first(sdr, gMgrDB.ctrls); elt; elt = sdr_list_next(sdr, elt)) { /* Step 1.1: Grab the descriptor. */ descObj = sdr_list_data(sdr, elt); sdr_read(sdr, (char *) &cur_desc, descObj, sizeof(cur_desc)); /* Step 1.2: Save the descriptor. */ cur_desc.descObj = descObj; /* Step 1.3: Allocate space for the item. */ if((data = (uint8_t*) STAKE(cur_desc.size)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_ctrls_init","Can't allocate %d bytes.", cur_desc.size); } else { /* Step 1.4: Grab the serialized item */ sdr_read(sdr, (char *) data, cur_desc.itemObj, cur_desc.size); /* Step 1.5: Deserialize the item. */ if((cur_item = ctrl_deserialize(data,cur_desc.size, &bytes_used)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_ctrls_init","Failed to deserialize ctrl.",NULL); } else { /* Step 1.6: Copy current descriptor to cur_rule. */ cur_item->desc = cur_desc; /* Step 1.7: Add rule to list of active rules. */ ADD_CTRL(cur_item); } /* Step 1.8: Release the serialized item. */ SRELEASE(data); /* Step 1.9: Note that we have another control. */ num++; } } sdr_end_xn(sdr); /* Step 2: Note to use number of controls read in. */ AMP_DEBUG_ALWAYS("", "Added %d Controls from DB.", num); } ctrl_exec_t* mgr_vdb_ctrl_find(mid_t *mid) { LystElt elt; ctrl_exec_t *cur = NULL; lockResource(&(gMgrVDB.ctrls_mutex)); for(elt = lyst_first(gMgrVDB.ctrls); elt; elt = lyst_next(elt)) { cur = (ctrl_exec_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { break; } cur = NULL; } unlockResource(&(gMgrVDB.ctrls_mutex)); return cur; } void mgr_vdb_ctrl_forget(mid_t *mid) { LystElt elt; ctrl_exec_t *cur = NULL; lockResource(&(gMgrVDB.ctrls_mutex)); for(elt = lyst_first(gMgrVDB.ctrls); elt; elt = lyst_next(elt)) { cur = (ctrl_exec_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { ctrl_release(cur); lyst_delete(elt); break; } } unlockResource(&(gMgrVDB.ctrls_mutex)); } uint32_t mgr_vdb_defgen_init(Sdr sdr, Object db, Lyst list, ResourceLock *mutex) { Object elt; Object descObj; def_gen_desc_t cur_desc; def_gen_t *cur_item; uint8_t *data; uint32_t bytes_used = 0; int num = 0; CHKZERO(sdr_begin_xn(sdr)); /* Step 1: Walk through report definitions. */ for (elt = sdr_list_first(sdr, db); elt; elt = sdr_list_next(sdr, elt)) { /* Step 1.1: Grab the descriptor. */ descObj = sdr_list_data(sdr, elt); sdr_read(sdr, (char *) &cur_desc, descObj, sizeof(cur_desc)); cur_desc.descObj = descObj; /* Step 1.2: Allocate space for the def. */ if((data = (uint8_t*) STAKE(cur_desc.size)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_defgen_init","Can't allocate %d bytes.", cur_desc.size); } else { /* Step 1.3: Grab the serialized def */ sdr_read(sdr, (char *) data, cur_desc.itemObj, cur_desc.size); /* Step 1.4: Deserialize into a rule object. */ if((cur_item = def_deserialize_gen(data, cur_desc.size, &bytes_used)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_defgen_init","Can't deserialize rpt.", NULL); } else { /* Step 1.5: Copy current descriptor to cur_rule. */ cur_item->desc = cur_desc; /* Step 1.6: Add report def to list of report defs. */ mgr_vdb_add(cur_item, list, mutex); /* Step 1.7: Note that we have read a new report.*/ num++; } /* Step 1.8: Release serialized rpt, we don't need it. */ SRELEASE(data); } } sdr_end_xn(sdr); return num; } def_gen_t *mgr_vdb_defgen_find(mid_t *mid, Lyst list, ResourceLock *mutex) { LystElt elt; def_gen_t *cur = NULL; lockResource(mutex); for(elt = lyst_first(list); elt; elt = lyst_next(elt)) { cur = (def_gen_t *) lyst_data(elt); if(mid_compare(cur->id, mid, 1) == 0) { break; } cur = NULL; } unlockResource(mutex); return cur; } void mgr_vdb_defgen_forget(mid_t *id, Lyst list, ResourceLock *mutex) { LystElt elt; def_gen_t *cur = NULL; lockResource(mutex); for(elt = lyst_first(list); elt; elt = lyst_next(elt)) { cur = (def_gen_t *) lyst_data(elt); if(mid_compare(cur->id, id, 1) == 0) { def_release_gen(cur); lyst_delete(elt); break; } } unlockResource(mutex); } /****************************************************************************** * * \par Function Name: mgr_vdb_destroy * * \par Cleans up mgr memory lists. * * \par Notes: * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ void mgr_vdb_destroy() { /* Step 1: Clear out data in lysts. */ def_lyst_clear(&(gMgrVDB.compdata), &(gMgrVDB.compdata_mutex), 1); ctrl_clear_lyst(&(gMgrVDB.ctrls), &(gMgrVDB.ctrls_mutex), 1); def_lyst_clear(&(gMgrVDB.macros), &(gMgrVDB.macros_mutex), 1); def_lyst_clear(&(gMgrVDB.reports), &(gMgrVDB.reports_mutex), 1); trl_lyst_clear(&(gMgrVDB.trls),&(gMgrVDB.trls_mutex), 1); srl_lyst_clear(&(gMgrVDB.srls),&(gMgrVDB.srls_mutex), 1); /* Step 2: Release resource locks. */ killResourceLock(&(gMgrVDB.compdata_mutex)); killResourceLock(&(gMgrVDB.ctrls_mutex)); killResourceLock(&(gMgrVDB.macros_mutex)); killResourceLock(&(gMgrVDB.reports_mutex)); killResourceLock(&(gMgrVDB.trls_mutex)); killResourceLock(&(gMgrVDB.srls_mutex)); } /****************************************************************************** * * \par Function Name: mgr_vdb_init * * \par Initializes mgr memory lists. * * \par Notes: * * \return 1 - Success. * -1 - Failure. * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. * 08/29/15 E. Birrane Update to include SQL account info. *****************************************************************************/ /* Initialize all of the VDB items. */ int mgr_vdb_init() { Sdr sdr = getIonsdr(); int result = 1; AMP_DEBUG_ENTRY("mgr_vdb_init","()",NULL); /* Step 0: Clean the memory. */ memset(&gMgrVDB, 0, sizeof(gMgrVDB)); /* Step 1: Create lysts and associated resource locks. */ if((gMgrVDB.compdata = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.compdata_mutex))) result = -1; mgr_vdb_compdata_init(sdr); if((gMgrVDB.ctrls = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.ctrls_mutex))) result = -1; mgr_vdb_ctrls_init(sdr); if((gMgrVDB.macros = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.macros_mutex))) result = -1; mgr_vdb_macros_init(sdr); if((gMgrVDB.reports = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.reports_mutex))) result = -1; mgr_vdb_reports_init(sdr); if((gMgrVDB.trls = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.trls_mutex))) result = -1; mgr_vdb_trls_init(sdr); if((gMgrVDB.srls = lyst_create()) == NULL) result = -1; if(initResourceLock(&(gMgrVDB.srls_mutex))) result = -1; mgr_vdb_srls_init(sdr); #ifdef HAVE_MYSQL if(initResourceLock(&(gMgrVDB.sqldb_mutex))) result = -1; mgr_vdb_sql_init(sdr); #endif AMP_DEBUG_EXIT("mgr_vdb_init","-->%d",result); return result; } void mgr_vdb_macros_init(Sdr sdr) { int num = 0; num = mgr_vdb_defgen_init(sdr, gMgrDB.macros, gMgrVDB.macros, &(gMgrVDB.macros_mutex)); AMP_DEBUG_ALWAYS("", "Added %d Macros from DB.", num); } def_gen_t *mgr_vdb_macro_find(mid_t *mid) { return mgr_vdb_defgen_find(mid, gMgrVDB.macros, &(gMgrVDB.macros_mutex)); } void mgr_vdb_macro_forget(mid_t *id) { mgr_vdb_defgen_forget(id, gMgrVDB.macros, &(gMgrVDB.macros_mutex)); } /****************************************************************************** * * \par Function Name: mgr_vdb_reports_init * * \par Read report definitions from the SDR database into memory lists. * * \param[in] sdr The SDR containing the report information. * * \par Notes: * * Modification History: * MM/DD/YY AUTHOR DESCRIPTION * -------- ------------ --------------------------------------------- * 06/10/13 E. Birrane Initial implementation. *****************************************************************************/ void mgr_vdb_reports_init(Sdr sdr) { int num = 0; num = mgr_vdb_defgen_init(sdr, gMgrDB.reports, gMgrVDB.reports, &(gMgrVDB.reports_mutex)); AMP_DEBUG_ALWAYS("", "Added %d Reports from DB.", num); } def_gen_t *mgr_vdb_report_find(mid_t *mid) { return mgr_vdb_defgen_find(mid, gMgrVDB.reports, &(gMgrVDB.reports_mutex)); } void mgr_vdb_report_forget(mid_t *id) { mgr_vdb_defgen_forget(id, gMgrVDB.reports, &(gMgrVDB.reports_mutex)); } void mgr_vdb_srls_init(Sdr sdr) { Object elt; Object descObj; srl_desc_t cur_descr; srl_t *cur_item; uint8_t *data = NULL; uint32_t bytes_used = 0; int num = 0; CHKVOID(sdr_begin_xn(sdr)); /* Step 1: Read in active rules. */ for (elt = sdr_list_first(sdr, gMgrDB.srls); elt; elt = sdr_list_next(sdr, elt)) { /* Step 1.1: Grab the descriptor. */ descObj = sdr_list_data(sdr, elt); sdr_read(sdr, (char *) &cur_descr, descObj, sizeof(cur_descr)); cur_descr.descObj = descObj; /* Step 1.2: Allocate space for the rule. */ if((data = (uint8_t*) STAKE(cur_descr.size)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_srls_init","Can't allocate %d bytes.", cur_descr.size); } else { /* Step 1.3: Grab the serialized rule */ sdr_read(sdr, (char *) data, cur_descr.itemObj, cur_descr.size); /* Step 1.4: Deserialize into a rule object. */ if((cur_item = srl_deserialize(data,cur_descr.size,&bytes_used)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_srls_init","Can't deserialize rule.", NULL); } else { /* Step 1.5: Copy current descriptor to cur_rule. */ cur_item->desc = cur_descr; /* Step 1.6: Add rule to list of active rules. */ ADD_SRL(cur_item); /* Step 1.7: Note that another rule has been read. */ num++; } /* Step 1.8: Release serialized rule, we don't need it. */ SRELEASE(data); } } sdr_end_xn(sdr); /* Step 2: Print to user total number of rules read.*/ AMP_DEBUG_ALWAYS("", "Added %d SRLs from DB.", num); } srl_t* mgr_vdb_srl_find(mid_t *mid) { LystElt elt; srl_t *cur = NULL; lockResource(&(gMgrVDB.srls_mutex)); for(elt = lyst_first(gMgrVDB.srls); elt; elt = lyst_next(elt)) { cur = (srl_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { break; } cur = NULL; } unlockResource(&(gMgrVDB.srls_mutex)); return cur; } void mgr_vdb_srl_forget(mid_t *mid) { LystElt elt; srl_t *cur = NULL; lockResource(&(gMgrVDB.srls_mutex)); for(elt = lyst_first(gMgrVDB.srls); elt; elt = lyst_next(elt)) { cur = (srl_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { srl_release(cur); lyst_delete(elt); break; } } unlockResource(&(gMgrVDB.srls_mutex)); } void mgr_vdb_trls_init(Sdr sdr) { Object elt; Object descObj; trl_desc_t cur_descr; trl_t *cur_item; uint8_t *data = NULL; uint32_t bytes_used = 0; int num = 0; CHKVOID(sdr_begin_xn(sdr)); /* Step 1: Read in active rules. */ for (elt = sdr_list_first(sdr, gMgrDB.trls); elt; elt = sdr_list_next(sdr, elt)) { /* Step 1.1: Grab the descriptor. */ descObj = sdr_list_data(sdr, elt); sdr_read(sdr, (char *) &cur_descr, descObj, sizeof(cur_descr)); cur_descr.descObj = descObj; /* Step 1.2: Allocate space for the rule. */ if((data = (uint8_t*) STAKE(cur_descr.size)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_trls_init","Can't allocate %d bytes.", cur_descr.size); } else { /* Step 1.3: Grab the serialized rule */ sdr_read(sdr, (char *) data, cur_descr.itemObj, cur_descr.size); /* Step 1.4: Deserialize into a rule object. */ if((cur_item = trl_deserialize(data,cur_descr.size,&bytes_used)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_trls_init","Can't deserialize rule.", NULL); } else { /* Step 1.5: Copy current descriptor to cur_rule. */ cur_item->desc = cur_descr; /* Step 1.6: Add rule to list of active rules. */ ADD_TRL(cur_item); /* Step 1.7: Note that another rule has been read. */ num++; } /* Step 1.8: Release serialized rule, we don't need it. */ SRELEASE(data); } } sdr_end_xn(sdr); /* Step 2: Print to user total number of rules read.*/ AMP_DEBUG_ALWAYS("", "Added %d TRLs from DB.", num); } trl_t* mgr_vdb_trl_find(mid_t *mid) { LystElt elt; trl_t *cur = NULL; lockResource(&(gMgrVDB.trls_mutex)); for(elt = lyst_first(gMgrVDB.trls); elt; elt = lyst_next(elt)) { cur = (trl_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { break; } cur = NULL; } unlockResource(&(gMgrVDB.trls_mutex)); return cur; } void mgr_vdb_trl_forget(mid_t *mid) { LystElt elt; trl_t *cur = NULL; lockResource(&(gMgrVDB.trls_mutex)); for(elt = lyst_first(gMgrVDB.trls); elt; elt = lyst_next(elt)) { cur = (trl_t *) lyst_data(elt); if(mid_compare(cur->mid, mid, 1) == 0) { trl_release(cur); lyst_delete(elt); break; } } unlockResource(&(gMgrVDB.trls_mutex)); } #ifdef HAVE_MYSQL void mgr_vdb_sql_init(Sdr sdr) { Object elt; Object descObj; uint8_t *data = NULL; uint8_t *cursor = NULL; CHKVOID(sdr_begin_xn(sdr)); /* Step 1: Grab the description for the account info. */ if((elt = sdr_list_first(sdr, gMgrDB.sqldb)) == 0) { sdr_end_xn(sdr); return; } if((descObj = sdr_list_data(sdr, elt)) == 0) { AMP_DEBUG_ERR("mgr_vdb_sql_init","Bad SQL Account descriptor.", NULL); sdr_end_xn(sdr); return; } lockResource(&(gMgrVDB.sqldb_mutex)); sdr_read(sdr, (char *) &(gMgrVDB.sqldb.desc), descObj, sizeof(gMgrVDB.sqldb.desc)); gMgrVDB.sqldb.desc.descObj = descObj; /* Step 2: Allocate and populate the descriptor field. */ if((data = (uint8_t*) STAKE(gMgrVDB.sqldb.desc.size)) == NULL) { AMP_DEBUG_ERR("mgr_vdb_sql_init","Can't allocate %d bytes.", gMgrVDB.sqldb.desc.size); unlockResource(&(gMgrVDB.sqldb_mutex)); sdr_end_xn(sdr); return; } sdr_read(sdr, (char *) data, gMgrVDB.sqldb.desc.itemObj, gMgrVDB.sqldb.desc.size); sdr_end_xn(sdr); /* Step 3: Populate the account info. */ cursor = &(data[0]); memcpy(gMgrVDB.sqldb.database, cursor, UI_SQL_DBLEN); cursor += UI_SQL_DBLEN; memcpy(gMgrVDB.sqldb.username, cursor, UI_SQL_ACCTLEN); cursor += UI_SQL_ACCTLEN; memcpy(gMgrVDB.sqldb.password, cursor, UI_SQL_ACCTLEN); cursor += UI_SQL_ACCTLEN; memcpy(gMgrVDB.sqldb.server, cursor, UI_SQL_SERVERLEN); cursor += UI_SQL_ACCTLEN; SRELEASE(data); unlockResource(&(gMgrVDB.sqldb_mutex)); /* Step 2: Print to user total number of rules read.*/ AMP_DEBUG_ALWAYS("", "Added SQL Account Information from DB.", NULL); } ui_db_t* mgr_vdb_sql_find() { ui_db_t *result = NULL; lockResource(&(gMgrVDB.sqldb_mutex)); result = &(gMgrVDB.sqldb); unlockResource(&(gMgrVDB.sqldb_mutex)); return result; } void mgr_vdb_sql_forget() { lockResource(&(gMgrVDB.sqldb_mutex)); memset(&(gMgrVDB.sqldb), 0, sizeof(ui_db_t)); unlockResource(&(gMgrVDB.sqldb_mutex)); } #endif
23.355441
102
0.59389
[ "object" ]
c0f5928461c45f1af2f47bef215048f2c398ded4
605
h
C
src/engine/keen/vorticon/ai/CVortiKid.h
vogonsorg/Commander-Genius
456703977d7e574af663fd03d4897728ede10058
[ "X11" ]
137
2015-01-01T21:04:51.000Z
2022-03-30T01:41:10.000Z
src/engine/keen/vorticon/ai/CVortiKid.h
vogonsorg/Commander-Genius
456703977d7e574af663fd03d4897728ede10058
[ "X11" ]
154
2015-01-01T16:34:39.000Z
2022-01-28T14:14:45.000Z
src/engine/keen/vorticon/ai/CVortiKid.h
vogonsorg/Commander-Genius
456703977d7e574af663fd03d4897728ede10058
[ "X11" ]
35
2015-03-24T02:20:54.000Z
2021-05-13T11:44:22.000Z
/* * CVortiKid.h * * Created on: 05.07.2010 * Author: gerstrong */ #ifndef CVORTIKID_H_ #define CVORTIKID_H_ #include "../CVorticonSpriteObject.h" #include "CPlayer.h" #include <vector> enum vort_baby_actions{ BABY_RUN, BABY_DYING }; class CVortikid : public CVorticonSpriteObject { public: CVortikid( CMap *p_map, Uint32 x, Uint32 y ); void getTouchedBy(CSpriteObject &theObject); void process(); void baby_jump(int big); private: vort_baby_actions state; direction_t dir; int jumpdectimer, xdectimer; int dietimer; char walkframe; int walktimer; }; #endif /* CVORTIKID_H_ */
16.351351
46
0.728926
[ "vector" ]
c0f63491787fae4c339ed36145a13cd68e590fc7
1,031
h
C
vsSenOpenGL/LearnOpenGL_GLFW/Sen_09_ModelViewProjection.h
SenonLi/VS_OpenGLSL_4.1
caaa4c66b0ca93128b2fa615f39c65f621b58803
[ "MIT" ]
1
2019-01-02T08:14:26.000Z
2019-01-02T08:14:26.000Z
vsSenOpenGL/LearnOpenGL_GLFW/Sen_09_ModelViewProjection.h
SenonLi/OpenGL_4.0_FreeSpace
caaa4c66b0ca93128b2fa615f39c65f621b58803
[ "MIT" ]
null
null
null
vsSenOpenGL/LearnOpenGL_GLFW/Sen_09_ModelViewProjection.h
SenonLi/OpenGL_4.0_FreeSpace
caaa4c66b0ca93128b2fa615f39c65f621b58803
[ "MIT" ]
null
null
null
#pragma once #ifndef __Sen_09_ModelViewProjection__ #define __Sen_09_ModelViewProjection__ #include "Support/SenAbstractGLFW.h" #include <soil/SOIL.h> // GLM Mathematics #define GLM_FORCE_SWIZZLE // Have to add this for new glm version without default structure initialization #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> class Sen_09_ModelViewProjection : public SenAbstractGLFW { public: Sen_09_ModelViewProjection(); virtual ~Sen_09_ModelViewProjection(); protected: void paintGL(void); void initGlfwGlewGL(); void finalize(); glm::mat4 model{ 1.0f }, view{ 1.0f }, projection{ 1.0f }; void initialVertices(); void initialBackgroundTexture(); void initialNewLayerTexture(); void bindBackgroundTexture(); void bindNewLayerTexture(); void initModelViewProjection(); void updateModelViewProjection(); void updateSecondModelViewProjection(); unsigned char* textureImagePtr; GLuint newLayerTexture, thirdLayerTexture; float viewCenter = -3.0f; }; #endif
22.911111
107
0.784675
[ "model" ]
8d0e2389caf9f68224b166beb4795cf4b11b265c
1,206
h
C
test/e2e/test_master/wxWidgets/include/wx/xrc/xh_auitoolb.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
test/e2e/test_master/wxWidgets/include/wx/xrc/xh_auitoolb.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
test/e2e/test_master/wxWidgets/include/wx/xrc/xh_auitoolb.h
BlueCannonBall/cppparser
9ae5f0c21268be6696532cf5b90c0384d6eb4940
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: wx/xrc/xh_toolb.h // Purpose: XML resource handler for wxAuiToolBar // Author: Rodolphe Suescun // Created: 2013-11-23 // Copyright: (c) 2013 Rodolphe Suescun // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_XH_AUITOOLB_H_ # define _WX_XH_AUITOOLB_H_ # include "wx/aui/auibar.h" # include "wx/menu.h" # include "wx/vector.h" # include "wx/xrc/xmlres.h" # if wxUSE_XRC && wxUSE_AUI class WXDLLIMPEXP_FWD_AUI wxAuiToolBar; class WXDLLIMPEXP_AUI wxAuiToolBarXmlHandler : public wxXmlResourceHandler { public: wxAuiToolBarXmlHandler(); wxObject* DoCreateResource() override; bool CanHandle(wxXmlNode* node) override; private: bool m_isInside; wxAuiToolBar* m_toolbar; wxSize m_toolSize; class MenuHandler : public wxEvtHandler { public: void OnDropDown(wxAuiToolBarEvent& event); unsigned RegisterMenu(wxAuiToolBar* toobar, int id, wxMenu* menu); private: wxVector<wxMenu*> m_menus; }; MenuHandler m_menuHandler; wxDECLARE_DYNAMIC_CLASS(wxAuiToolBarXmlHandler); }; # endif #endif
30.15
77
0.641791
[ "vector" ]
8d14b7ccc20d07efeaf51d84bc9c9d38de9a0c93
2,016
h
C
More/Plotting/Pulsar/DigitiserCountsPlot.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
null
null
null
More/Plotting/Pulsar/DigitiserCountsPlot.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
null
null
null
More/Plotting/Pulsar/DigitiserCountsPlot.h
rwharton/psrchive_dsn
9584862167154fa48db89b86151c4221ad4bb96b
[ "AFL-2.1" ]
1
2020-02-13T20:08:14.000Z
2020-02-13T20:08:14.000Z
/*************************************************************************** * * Copyright (C) 2007 by David Smith * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ #ifndef DIGITISER_COUNTS_PLOT_H_ #define DIGITISER_COUNTS_PLOT_H_ #include "Pulsar/SimplePlot.h" #include <Pulsar/DigitiserCounts.h> #include <vector> using std::pair; using std::vector; namespace Pulsar { //! Plots a histogram of the DigitiserCounts class DigitiserCountsPlot : public SimplePlot { public: DigitiserCountsPlot(); TextInterface::Parser *get_interface(); //! disable default pre-processing of Plot base class void preprocess (Archive* archive); class Interface : public TextInterface::To<DigitiserCountsPlot> { public: Interface( DigitiserCountsPlot *s_instance = NULL ); }; void CheckCounts( const Archive *data ); void prepare( const Archive *data ); void draw( const Archive *data ); std::string get_xlabel( const Archive *data ); std::string get_ylabel( const Archive *data ); pair<int,int> get_srange() const { return srange; } void set_srange( const pair<int,int> &s_srange ) { srange = s_srange; } void set_srange( int fsub, int lsub ) { set_srange( pair<int,int>( fsub, lsub) ); } int get_subint( void ) const { return subint; } void set_subint( int s_subint ) { subint = s_subint; } bool get_logscale () const { return logscale; } void set_logscale (bool f) { logscale = f; } // fraction of the maximum below which data are considered zero double get_zero_threshold () const { return zero_threshold; } void set_zero_threshold (double f) { zero_threshold = f; } private: double zero_threshold; bool logscale; float min_count; float max_count; float y_jump; int first_nz; int last_nz; int subint; pair<int,int> srange; bool valid_data; }; } #endif
22.909091
87
0.625992
[ "vector" ]
8d1952d71fdcbeed855502d5cdc052f13edb73af
8,703
h
C
cpp/include/ray/api.h
vermashresth/ray
9aaaa508cacb90a5be714478970b2191aaa43170
[ "Apache-2.0" ]
1
2020-11-14T19:25:41.000Z
2020-11-14T19:25:41.000Z
cpp/include/ray/api.h
vermashresth/ray
9aaaa508cacb90a5be714478970b2191aaa43170
[ "Apache-2.0" ]
3
2021-06-08T21:46:35.000Z
2022-03-12T00:35:21.000Z
cpp/include/ray/api.h
vermashresth/ray
9aaaa508cacb90a5be714478970b2191aaa43170
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <ray/api/generated/actor_funcs.generated.h> #include <ray/api/generated/create_funcs.generated.h> #include <ray/api/generated/funcs.generated.h> #include <ray/api/ray_runtime.h> #include <msgpack.hpp> #include "ray/core.h" namespace ray { namespace api { template <typename T> class RayObject; template <typename T> class RayActor; class WaitResult; class Ray { public: /// Initialize Ray runtime. static void Init(); /// Store an object in the object store. /// /// \param[in] obj The object which should be stored. /// \return RayObject A reference to the object in the object store. template <typename T> static RayObject<T> Put(const T &obj); /// Get a list of objects from the object store. /// This method will be blocked until all the objects are ready. /// /// \param[in] ids The object id array which should be got. /// \return shared pointer array of the result. template <typename T> static std::vector<std::shared_ptr<T>> Get(const std::vector<ObjectID> &ids); /// Get a list of objects from the object store. /// This method will be blocked until all the objects are ready. /// /// \param[in] objects The object array which should be got. /// \return shared pointer array of the result. template <typename T> static std::vector<std::shared_ptr<T>> Get(const std::vector<RayObject<T>> &ids); /// Wait for a list of RayObjects to be locally available, /// until specified number of objects are ready, or specified timeout has passed. /// /// \param[in] ids The object id array which should be waited. /// \param[in] num_objects The minimum number of objects to wait. /// \param[in] timeout_ms The maximum wait time in milliseconds. /// \return Two arrays, one containing locally available objects, one containing the /// rest. static WaitResult Wait(const std::vector<ObjectID> &ids, int num_objects, int timeout_ms); /// Include the `Call` methods for calling remote functions. #include "api/generated/call_funcs.generated.h" /// Include the `CreateActor` methods for creating actors. #include "api/generated/create_actors.generated.h" private: static RayRuntime *runtime_; static std::once_flag is_inited_; /// Used by RayObject to implement .Get() template <typename T> static std::shared_ptr<T> Get(const RayObject<T> &object); template <typename ReturnType, typename FuncType, typename ExecFuncType, typename... ArgTypes> static RayObject<ReturnType> CallInternal(FuncType &func, ExecFuncType &exec_func, ArgTypes &... args); template <typename ReturnType, typename FuncType, typename ExecFuncType, typename... ArgTypes> static RayActor<ReturnType> CreateActorInternal(FuncType &func, ExecFuncType &exec_func, ArgTypes &... args); template <typename ReturnType, typename ActorType, typename FuncType, typename ExecFuncType, typename... ArgTypes> static RayObject<ReturnType> CallActorInternal(FuncType &actor_func, ExecFuncType &exec_func, RayActor<ActorType> &actor, ArgTypes &... args); /// Include the `Call` methods for calling actor methods. /// Used by RayActor to implement .Call() #include "api/generated/call_actors.generated.h" template <typename T> friend class RayObject; template <typename ActorType> friend class RayActor; }; } // namespace api } // namespace ray // --------- inline implementation ------------ #include <ray/api/arguments.h> #include <ray/api/ray_actor.h> #include <ray/api/ray_object.h> #include <ray/api/serializer.h> #include <ray/api/wait_result.h> namespace ray { namespace api { template <typename T> inline static std::vector<ObjectID> RayObjectsToObjectIDs( const std::vector<RayObject<T>> &ray_objects) { std::vector<ObjectID> object_ids; for (auto it = ray_objects.begin(); it != ray_objects.end(); it++) { object_ids.push_back(it->ID()); } return object_ids; } template <typename T> inline RayObject<T> Ray::Put(const T &obj) { std::shared_ptr<msgpack::sbuffer> buffer(new msgpack::sbuffer()); msgpack::packer<msgpack::sbuffer> packer(buffer.get()); Serializer::Serialize(packer, obj); auto id = runtime_->Put(buffer); return RayObject<T>(id); } template <typename T> inline std::shared_ptr<T> Ray::Get(const RayObject<T> &object) { auto packed_object = runtime_->Get(object.ID()); msgpack::unpacker unpacker; unpacker.reserve_buffer(packed_object->size()); memcpy(unpacker.buffer(), packed_object->data(), packed_object->size()); unpacker.buffer_consumed(packed_object->size()); std::shared_ptr<T> return_object(new T); Serializer::Deserialize(unpacker, return_object.get()); return return_object; } template <typename T> inline std::vector<std::shared_ptr<T>> Ray::Get(const std::vector<ObjectID> &ids) { auto result = runtime_->Get(ids); std::vector<std::shared_ptr<T>> return_objects; return_objects.reserve(result.size()); for (auto it = result.begin(); it != result.end(); it++) { msgpack::unpacker unpacker; unpacker.reserve_buffer((*it)->size()); memcpy(unpacker.buffer(), (*it)->data(), (*it)->size()); unpacker.buffer_consumed((*it)->size()); std::shared_ptr<T> obj(new T); Serializer::Deserialize(unpacker, obj.get()); return_objects.push_back(obj); } return return_objects; } template <typename T> inline std::vector<std::shared_ptr<T>> Ray::Get(const std::vector<RayObject<T>> &ids) { auto object_ids = RayObjectsToObjectIDs<T>(ids); return Get<T>(object_ids); } inline WaitResult Ray::Wait(const std::vector<ObjectID> &ids, int num_objects, int timeout_ms) { return runtime_->Wait(ids, num_objects, timeout_ms); } template <typename ReturnType, typename FuncType, typename ExecFuncType, typename... ArgTypes> inline RayObject<ReturnType> Ray::CallInternal(FuncType &func, ExecFuncType &exec_func, ArgTypes &... args) { std::shared_ptr<msgpack::sbuffer> buffer(new msgpack::sbuffer()); msgpack::packer<msgpack::sbuffer> packer(buffer.get()); Arguments::WrapArgs(packer, args...); RemoteFunctionPtrHolder ptr; ptr.function_pointer = reinterpret_cast<uintptr_t>(func); ptr.exec_function_pointer = reinterpret_cast<uintptr_t>(exec_func); auto returned_object_id = runtime_->Call(ptr, buffer); return RayObject<ReturnType>(returned_object_id); } template <typename ReturnType, typename FuncType, typename ExecFuncType, typename... ArgTypes> inline RayActor<ReturnType> Ray::CreateActorInternal(FuncType &create_func, ExecFuncType &exec_func, ArgTypes &... args) { std::shared_ptr<msgpack::sbuffer> buffer(new msgpack::sbuffer()); msgpack::packer<msgpack::sbuffer> packer(buffer.get()); Arguments::WrapArgs(packer, args...); RemoteFunctionPtrHolder ptr; ptr.function_pointer = reinterpret_cast<uintptr_t>(create_func); ptr.exec_function_pointer = reinterpret_cast<uintptr_t>(exec_func); auto returned_actor_id = runtime_->CreateActor(ptr, buffer); return RayActor<ReturnType>(returned_actor_id); } template <typename ReturnType, typename ActorType, typename FuncType, typename ExecFuncType, typename... ArgTypes> inline RayObject<ReturnType> Ray::CallActorInternal(FuncType &actor_func, ExecFuncType &exec_func, RayActor<ActorType> &actor, ArgTypes &... args) { std::shared_ptr<msgpack::sbuffer> buffer(new msgpack::sbuffer()); msgpack::packer<msgpack::sbuffer> packer(buffer.get()); Arguments::WrapArgs(packer, args...); RemoteFunctionPtrHolder ptr; MemberFunctionPtrHolder holder = *(MemberFunctionPtrHolder *)(&actor_func); ptr.function_pointer = reinterpret_cast<uintptr_t>(holder.value[0]); ptr.exec_function_pointer = reinterpret_cast<uintptr_t>(exec_func); auto returned_object_id = runtime_->CallActor(ptr, actor.ID(), buffer); return RayObject<ReturnType>(returned_object_id); } #include <ray/api/generated/exec_funcs.generated.h> #include <ray/api/generated/call_funcs_impl.generated.h> #include <ray/api/generated/create_actors_impl.generated.h> #include <ray/api/generated/call_actors_impl.generated.h> } // namespace api } // namespace ray
37.512931
90
0.681374
[ "object", "vector" ]
8d2719885a4cd1e3159e00ac975743d172c2eb46
411
h
C
graphs/c_graph.h
habs1337/graphs
092f2e12ee297a20a8a1efd562299ce1535050ab
[ "MIT" ]
null
null
null
graphs/c_graph.h
habs1337/graphs
092f2e12ee297a20a8a1efd562299ce1535050ab
[ "MIT" ]
null
null
null
graphs/c_graph.h
habs1337/graphs
092f2e12ee297a20a8a1efd562299ce1535050ab
[ "MIT" ]
null
null
null
class c_graph { vector<int> m_graph; int** m_matrix_of_adjacency = nullptr; unsigned short m_graph_size = 0, m_matrix_of_adjency_size = 0; void init_ptr(unsigned short& size, const int& n, int**& arr ); void push_values( ); void create_matrix_of_adhency( ); public: void show_edges( ); void show_matrix_of_adjacency( ); void transitive_graph( ); c_graph( ); c_graph( const int& n ); ~c_graph( ); };
25.6875
64
0.717762
[ "vector" ]
8d2934d39897b2ec1f759238d0e0d524739f0020
3,235
h
C
cpp/open3d/visualization/visualizer/GuiSettingsView.h
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
1
2021-08-06T06:16:08.000Z
2021-08-06T06:16:08.000Z
cpp/open3d/visualization/visualizer/GuiSettingsView.h
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
null
null
null
cpp/open3d/visualization/visualizer/GuiSettingsView.h
leomariga/Open3D
d197339fcd29ad0803a182ef8953d89e563f94d7
[ "MIT" ]
1
2021-07-23T15:15:04.000Z
2021-07-23T15:15:04.000Z
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #pragma once #include <functional> #include <memory> #include <string> #include "open3d/visualization/gui/Layout.h" namespace open3d { namespace visualization { namespace gui { class Button; class Checkbox; class Combobox; class ColorEdit; class CollapsableVert; class Slider; class VectorEdit; } // namespace gui class GuiSettingsModel; class GuiSettingsView : public gui::Vert { public: GuiSettingsView(GuiSettingsModel& model, const gui::Theme& theme, const std::string& resource_path, std::function<void(const char*)> on_load_ibl); void ShowFileMaterialEntry(bool show); void Update(); private: GuiSettingsModel& model_; std::function<void(const char*)> on_load_ibl_; std::shared_ptr<gui::Combobox> lighting_profile_; std::shared_ptr<gui::Checkbox> show_axes_; std::shared_ptr<gui::Checkbox> show_ground_; std::shared_ptr<gui::ColorEdit> bg_color_; std::shared_ptr<gui::Checkbox> show_skybox_; std::shared_ptr<gui::CollapsableVert> advanced_; std::shared_ptr<gui::Checkbox> ibl_enabled_; std::shared_ptr<gui::Checkbox> sun_enabled_; std::shared_ptr<gui::Combobox> ibls_; std::shared_ptr<gui::Slider> ibl_intensity_; std::shared_ptr<gui::Slider> sun_intensity_; std::shared_ptr<gui::VectorEdit> sun_dir_; std::shared_ptr<gui::Checkbox> sun_follows_camera_; std::shared_ptr<gui::ColorEdit> sun_color_; std::shared_ptr<gui::Combobox> material_type_; std::shared_ptr<gui::Combobox> prefab_material_; std::shared_ptr<gui::ColorEdit> material_color_; std::shared_ptr<gui::Button> reset_material_color_; std::shared_ptr<gui::Slider> point_size_; }; } // namespace visualization } // namespace open3d
35.944444
80
0.667079
[ "model" ]
8d3e1ff6ebb809c7a0be656dd9c3fc0d8d5bb226
29,911
c
C
kernel/huawei/hwp7/drivers/hisi/modem/ps/comm/comm/NFEXT/Interpeak/ip_net2-6.8/osconfig/vxworks/src/net/usrNetBridgeCfg.c
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
1
2020-04-03T14:00:34.000Z
2020-04-03T14:00:34.000Z
kernel/huawei/hwp7/drivers/hisi/modem/ps/comm/comm/NFEXT/Interpeak/ip_net2-6.8/osconfig/vxworks/src/net/usrNetBridgeCfg.c
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
null
null
null
kernel/huawei/hwp7/drivers/hisi/modem/ps/comm/comm/NFEXT/Interpeak/ip_net2-6.8/osconfig/vxworks/src/net/usrNetBridgeCfg.c
NightOfTwelve/android_device_huawei_hwp7
a0a1c28e44210ce485a4177ac53d3fd580008a1e
[ "Apache-2.0" ]
1
2020-04-03T14:00:39.000Z
2020-04-03T14:00:39.000Z
/* usrNetBridgeCfg.c - Simple Learning Bridge init routines */ /* Copyright 2002-2005 Wind River Systems, Inc. */ /* modification history -------------------- 02b,26nov07,tlu Replace INCLUDE_IPCOM_USE_INET6 by INET6 02a,14nov06,tlu Remove un-used variable addr (defect 69139) 01z,18sep06,tlu Un-comment ipDetach and ip6Detach 01y,15aug06,tlu Ported to IPNET stack 01x,24jun05,svk Fix another diab compiler warning 01w,27may05,svk Fix compilation warnings 01v,28apr05,zhu Set IFF_IFNET6_UP before assigning IPv6 address 01u,19mar05,zhu Changed the string format to be consistent with NAT and Firewall 01t,28mar05,svk Allow bridge to attach to IPv6 stack 01s,02feb05,svk WDB END handling unnecessary if WDB_END_DEVICE_NAME and WDB_END_DEVICE_UNIT are defined 01r,19oct04,svk Include config.h for command-line BSP build 01q,07oct04,svk Detach bridge ports from IPv6 stack also 01p,13sep04,svk Fix compilation warnings 01o,06jul04,zhu Updated for dual stack 01n,02jul03,myz Added INCLUDE_WDB_COMM_END macro to the WDB END check 01m,03jun03,myz Added WDB END handling when its interface is a bridge port 01l,30may03,myz Modify promiscuousModeSet to use driver's ioctl to set the mode 01k,15may03,svk Added includes needed for cmdline build, fixed warnings 01j,25apr03,zhu updated copyright 01i,10may02,svk Changed mirrorInit() and promiscuousModeSet() to be callable from outside configlette 01h,25apr02,svk Coding standard and linked list changes 01g,24apr02,vks code-review changes: linked-list usage, project facility parameter dependency removal (usrNetBridgeInit() signature), several minor changes as per coding standards. 01f,22apr02,svk Replace ports buffer on stack with malloc'ed buffer 01e,11apr02,svk Add function to use socket ioctl. 01d,10apr02,svk More minor changes. 01c,10apr02,vks merged bridge and mirror configlettes 01b,10apr02,svk Various minor changes. 01a,09apr02,svk written */ /* DESCRIPTION This file is used to configure and initialize the Simple Learning Bridge. INCLUDE FILES: bridge.h, mirrorEnd.h NOMANUAL */ /* includes */ #include <ipProto.h> #include "wrn/bridge/bridge.h" #include "wrn/bridge/mirrorEnd.h" #include "private/muxLibP.h" #include <ipcom_sock.h> #include <ipcom_sock2.h> #include <ipcom_sock6.h> #include <ipcom_vxworks.h> /* defines */ #define MIRROR_NAME_MAX 15 /* max size of mirror name */ #define MIRROR_LOAD_STRING "" /* used in mirror muxDevLoad */ #define PORT_SEPARATOR "," /* separator in port string */ /* typedefs */ typedef struct /* bridge node - BRIDGE_NODE */ { NODE node; /* must be first member for lstLib */ char devName[END_NAME_MAX]; /* device name */ int unit; /* unit number */ } BRIDGE_NODE; #ifdef INCLUDE_WDB #if ((WDB_COMM_TYPE == WDB_COMM_END || defined(INCLUDE_WDB_COMM_END)) && \ !defined(WDB_END_DEVICE_NAME) && !defined(WDB_END_DEVICE_UNIT)) LOCAL END_TBL_ENTRY* pSavedEndTbl = NULL; LOCAL int savedTblEntries = 0; LOCAL STATUS bridgeWdbEndEntryFind (BRIDGE_NODE *); LOCAL void bridgeEndTblRestore (WIND_TCB *); IMPORT END_TBL_ENTRY endDevTbl[]; #endif #endif /* INCLUDE_WDB */ /* imports */ IMPORT END_OBJ* mirrorEndLoad (char*, void*); IMPORT void mirrorBaseParamsSet (char*, int); /* forward declarations */ LOCAL STATUS portsStringParse (char *, LIST*); LOCAL STATUS bridgePortsInit(LIST*); LOCAL void devicePromiscuousModeSet(END_OBJ *); STATUS mirrorInit (char *, int, char *, int, char*, int); STATUS promiscuousModeSet (char *, int); /******************************************************************************* * * usrNetBridgeInit - Simple Learning Bridge initialization * * This routine initializes the bridge. It first parses the bridge ports * string argument, and populates a linked list. It then initializes the * bridge, bridge ports, and the mirror device. * * RETURNS: * OK, or * ERROR if there is a problem in initializing bridge * * NOMANUAL */ STATUS usrNetBridgeInit ( char* pPortString, /* interfaces to be configured as bridge ports */ /* e.g., "fei0,fei1,elPci0" */ char* pAddr, /* IP address for this bridge */ int mask, /* netmask for this bridge */ char* pAddrv6, /* IPv6 address for this bridge */ int prefixLen /* IPv6 prefix length for this bridge */ ) { LIST bridgePortList; /* list of BRIDGE_NODEs */ BRIDGE_NODE* pFirstNode; /* first node in the list */ /* Initialize the list */ lstInit(&bridgePortList); /* Parse the port string and populate the list */ if (portsStringParse(pPortString, &bridgePortList) != OK) { printf("portsStringParse failed!\n"); lstFree(&bridgePortList); return ERROR; } /* Initialize the bridge */ if (bridgeInit() != OK) { printf("bridgeInit failed!\n"); lstFree(&bridgePortList); return ERROR; } /* Initialize the bridge ports */ if (bridgePortsInit(&bridgePortList) != OK) { printf("bridgePortsInit failed!\n"); lstFree(&bridgePortList); return ERROR; } /* Initialize the mirror interface. * * NOTE: The first bridge port's device name and number is used * to initialize the mirror interface. */ pFirstNode = (BRIDGE_NODE*) lstFirst(&bridgePortList); if (mirrorInit(pFirstNode->devName, pFirstNode->unit, pAddr, mask, pAddrv6, prefixLen) != OK) { printf("mirrorInit failed!\n"); lstFree(&bridgePortList); return ERROR; } /* Cleanup */ lstFree(&bridgePortList); return OK; } /******************************************************************************* * * portsStringParse - Parse the string for device names and unit numbers * * This routine parses the given string to extract the device names and * unit numbers. The extracted values are stored in a linked list. * * RETURNS: * OK, or * ERROR if there is a problem in parsing the port string * * NOMANUAL */ LOCAL STATUS portsStringParse ( char* pPorts, /* string to parse for bridge ports */ LIST* pBridgePortList /* linked list to hold bridge ports */ ) { char* pPortsBuf = NULL; /* buffer to hold copy of ports string */ char* ptr = NULL; /* pointer used to copy ports string */ char* token = NULL; /* one token in the ports string */ STATUS status = OK; /* return status */ BRIDGE_NODE* pNode; /* one node in the list */ char * pHolder = NULL; /* string holder */ char * pStrEnd = NULL; /* string end holder */ /* Parameter check */ if (pPorts == NULL) { printf("Bridge port string is NULL!\n"); return ERROR; } if (pBridgePortList == NULL) { printf("List of bridge ports is NULL!\n"); return ERROR; } /* Is the bridge port string configuration parameter specified? */ if (strlen(pPorts) == 0) { printf("List of bridge ports not specified! -\n"); printf("Please set the bridge configuration parameter BRIDGE_PORTS.\n"); printf("This must a list of comma-separated device name and unit \ number pairs.\nFor example: \"fei,0,fei,1,elPci,0\"\n"); return ERROR; } /* * The for-loop below uses strtok() to parse the list of bridge ports. * strtok() modifies the string given to it. Therefore, make a copy of the * string and give strtok() the copy to work with. */ pPortsBuf = malloc(strlen(pPorts) + 1); for (ptr = pPortsBuf; *pPorts != '\0'; pPorts++) { if (!isspace((int)*pPorts)) /* ignore space */ *ptr++ = *pPorts; } *ptr = '\0'; for (token = strtok_r(pPortsBuf, PORT_SEPARATOR, &pHolder); token != NULL; token = strtok_r(NULL, PORT_SEPARATOR, &pHolder)) { /* Create a new node */ pNode = (BRIDGE_NODE*) malloc(sizeof(BRIDGE_NODE)); bzero((char*) pNode, sizeof(BRIDGE_NODE)); if (strlen(token) > END_NAME_MAX - 1) { printf("Device name too long in bridge port string: %s\n", token); status = ERROR; break; } strcpy(pNode->devName, token); if ((token = strtok_r(NULL, PORT_SEPARATOR, &pHolder)) == NULL) { printf("Unit number missing in bridge port string\n"); printf("Specify device name and unit number pairs. e.g., fei,0,fei,1\n"); status = ERROR; break; } pNode->unit = strtol(token, &pStrEnd, 10); if (*pStrEnd) { printf("Invalid unit number in bridge port string: %s\n", token); status = ERROR; break; } if (endFindByName(pNode->devName,pNode->unit) == NULL) { printf("Can't find device %s%d\n", pNode->devName, pNode->unit); status = ERROR; break; } /* Add the node to the list */ lstAdd(pBridgePortList, (NODE *) pNode); } /* for */ /* Cleanup */ if (pPortsBuf != NULL) free(pPortsBuf); return status; } /******************************************************************************* * * bridgePortsInit - Bridge ports initialization * * This routine walks through the list of interfaces to initialize as * bridge ports and sets each interface to promicuous mode before adding it * as a bridge port. * * RETURNS: * OK, or * ERROR if there is a problem in initializing bridge ports * * NOMANUAL */ LOCAL STATUS bridgePortsInit ( LIST* pBridgePortList /* list of interfaces */ ) { STATUS status = OK; /* return status */ BRIDGE_NODE* pNode = NULL; /* one node in the list */ END_OBJ * pEnd = NULL; char ifName[END_NAME_MAX * 2]; char * oldifname; #ifdef INCLUDE_WDB #if ((WDB_COMM_TYPE == WDB_COMM_END || defined(INCLUDE_WDB_COMM_END)) && \ !defined(WDB_END_DEVICE_NAME) && !defined(WDB_END_DEVICE_UNIT)) BRIDGE_NODE bridgeWdbIf; #endif #endif /* Parameter check */ if (pBridgePortList == NULL) { printf("List of bridge ports is NULL!\n"); return ERROR; } #ifdef INCLUDE_WDB #if ((WDB_COMM_TYPE == WDB_COMM_END || defined(INCLUDE_WDB_COMM_END)) && \ !defined(WDB_END_DEVICE_NAME) && !defined(WDB_END_DEVICE_UNIT)) /* The WDB END communication requires a standard IP stack attached to the * interface to retrive the IP address and answering ARP requests in the * task mode although it has its own UDP lite stack to handle the WDB * traffics. With concerned interface joined as bridge port, that IP * stack is no longer available. So we need to use the bridge's virtual * interface mirror0 as WDB END's new interface if the original network * interface becomes as a bridge port in order to keep WDB END communication * going. This also implies the mirror0 should be initialized before WDB. * If the WDB END is intialized before the bridge, it may just work if * the IP address is not changed. In that case, the WDB protocol is the * first SNARF protocol to attach the MUX, therefore will intercept all * the traffic bound to that interface first */ /* find the original designated WDB END interface */ bzero(bridgeWdbIf.devName,END_NAME_MAX); if (bridgeWdbEndEntryFind(&bridgeWdbIf) != OK) bridgeWdbIf.unit = NONE; else { /* Found the WDB interface. Do nothing if WDB is already initialized */ if (taskNameToId("tWdbTask") != ERROR) bridgeWdbIf.unit = NONE; } #endif #endif for (pNode = (BRIDGE_NODE*)lstFirst(pBridgePortList); pNode != NULL; pNode = (BRIDGE_NODE*)lstNext((NODE*) pNode)) { sprintf(ifName, "%s%d", pNode->devName, pNode->unit); oldifname = (char *)ipcom_get_ip_if_name(ifName); if (oldifname != IP_NULL) { ipDetach(pNode->unit, pNode->devName); #ifdef INET6 ip6Detach(pNode->unit, pNode->devName); #endif /* INET6 */ } #ifdef INCLUDE_WDB #if ((WDB_COMM_TYPE == WDB_COMM_END || defined(INCLUDE_WDB_COMM_END)) && \ !defined(WDB_END_DEVICE_NAME) && !defined(WDB_END_DEVICE_UNIT)) /* check if it is the interface used by WDB */ if ( (strcmp(pNode->devName,bridgeWdbIf.devName) == 0) && (pNode->unit == bridgeWdbIf.unit) ) { /* yes, one of the bridge port is used by WDB */ /* The WDB END interface selection algorithm is that it searches * the endDevTbl to see if one of them matches the boot device. * If does, then the boot device is selected. If doesn't, then the * first one in the endDevTbl is selected. The mirror0 is always * not in the endDevTbl. In order to make mirror0 as WDB END * interface, we use this hack, first save the entire endDevTbl, * re-intialize the first entry with mirror0 and mark the second * entry as end entry, Then the endDevTbl will be restored back * when the "tWdbTask" is created. */ if (pSavedEndTbl == NULL) { END_TBL_ENTRY * pDevTbl; int count; for (count = 0, pDevTbl = endDevTbl; pDevTbl->endLoadFunc != END_TBL_END; pDevTbl++, count++); pSavedEndTbl =(END_TBL_ENTRY *)malloc( count * sizeof(END_TBL_ENTRY)); bcopy((char *)endDevTbl,(char *)pSavedEndTbl, count * sizeof(END_TBL_ENTRY)); savedTblEntries = count; endDevTbl[0].unit = MIRROR_STACK_UNIT_NUM; endDevTbl[0].endLoadFunc = mirrorEndLoad; endDevTbl[0].endLoadString = MIRROR_LOAD_STRING; endDevTbl[0].endLoan = FALSE; endDevTbl[0].pBSP = NULL; endDevTbl[1].unit = 0; endDevTbl[1].endLoadFunc = END_TBL_END; endDevTbl[1].endLoadString = NULL; endDevTbl[1].endLoan = FALSE; endDevTbl[1].pBSP = NULL; endDevTbl[1].processed = FALSE; taskCreateHookAdd ((FUNCPTR)bridgeEndTblRestore); } } #endif #endif /* Set the port to promiscuous mode */ pEnd = endFindByName(pNode->devName,pNode->unit); if (pEnd == NULL) { printf("Can't set device %s%d to promiscuous mode\n", pNode->devName, pNode->unit); status = ERROR; break; } netJobAdd ((FUNCPTR)devicePromiscuousModeSet,(int)pEnd,0,0,0,0); /* Add the port to the bridge */ if (bridgePortAdd (pNode->devName, pNode->unit) != OK) { printf ("bridgePortAdd failed for device %s%d\n", pNode->devName, pNode->unit); status = ERROR; break; } } /* for */ return status; } /******************************************************************************* * * mirrorInit - Mirror interface initialization * * This routine initializes the mirror interface by performing the * following tasks: * * 1. Passes the specified device name and unit number to mirrorBaseParamsSet(). * These values are needed for mirrorEnetAddrGet(). * 2. Loads two mirror END drivers, and attaches one to the network stack and * the other to the bridge. * 3. Assigns specified IP address and mask to the mirror device 0 (the mirror * attached to the IP stack). * * RETURNS: * OK, or * ERROR if there is a problem in initializing the mirror interface * * NOMANUAL */ STATUS mirrorInit ( char* pDevName, /* name of a bridge port device */ int unit, /* unit number of a bridge port device */ char* pAddr, /* IP address of bridge */ int mask, /* netmask of bridge */ char* pAddrv6, /* IPv6 address of bridge */ int prefixLen /* IPv6 prefix length */ ) { void* pMuxCookie; /* cookie returned by muxDevLoad */ char mirrorDevName[MIRROR_NAME_MAX]; /* mirror name and number */ END_OBJ* pEnd; /* end object from cookie */ BOOL gotAddrv4 = FALSE; /* IPv4 address specified? */ BOOL gotAddrv6 = FALSE; /* IPv6 address specified? */ Ip_fd fd; struct Ip_ifreq ifr; /* Parameter check */ if (pDevName == NULL) { printf("Name of bridge port device is NULL!\n"); return ERROR; } /* Is the bridge address configuration parameter specified? */ if ((pAddr != NULL) && (pAddr[0] != 0)) gotAddrv4 = TRUE; if ((pAddrv6 != NULL) && (pAddrv6[0] != 0)) gotAddrv6 = TRUE; #ifdef INET6 if (!gotAddrv4 && !gotAddrv6) { /* In dual mode, neither IPv4 nor IPv6 address was specified */ printf("IP address of the bridge not specified! Specify IPv4" " and/or IPv6 address -\n"); printf("Please set the bridge configuration parameters BRIDGE_IP_ADDR" " and/or\nBRIDGE_IPV6_ADDR. For example:\n"); printf("BRIDGE_IP_ADDR - \"10.11.12.1\"" " BRIDGE_IPV6_ADDR - \"2002:C000:0240::66\"\n"); return ERROR; } #else if (!gotAddrv4) { /* In IPv4-only mode, no IPv4 address was specified */ printf("IP address of the bridge not specified! -\n"); printf("Please set the bridge configuration parameter BRIDGE_IP_ADDR.\n"); printf("For example: \"10.11.12.1\"\n"); return ERROR; } #endif /* INET6 */ /* * Set the device name and the unit number that will be * used by mirrorEnetAddrGet() */ mirrorBaseParamsSet (pDevName, unit); sprintf (mirrorDevName, "%s%d", MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); /* Load the network stack side of the mirror END driver */ pMuxCookie = muxDevLoad (MIRROR_STACK_UNIT_NUM, mirrorEndLoad, MIRROR_LOAD_STRING, FALSE, NULL); if (pMuxCookie == NULL) { printf ("muxDevLoad failed for %s\n", mirrorDevName); return ERROR; } if (muxDevStart (pMuxCookie) != OK) { printf ("muxDevStart failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } /* Attach TCP/IP stack to the mirror END */ #ifdef INET6 if (gotAddrv4) { #endif if (ipAttach (MIRROR_STACK_UNIT_NUM, MIRROR_DEV_NAME) != OK) { printf("ipAttach failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } fd = ipcom_socket(IP_AF_INET, IP_SOCK_DGRAM, 0); if (fd == IP_INVALID_SOCKET) { printf("Failed to open a socket\n"); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } memset(&ifr, 0, sizeof(struct Ip_ifreq)); strcpy(ifr.ifr_name, ipcom_get_ip_if_name(mirrorDevName)); /* Bring the interface up */ if (ipcom_socketioctl(fd, IP_SIOCGIFFLAGS, &ifr) < 0) { printf("ifconfig: failed to get interface flags"); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } IP_BIT_SET(ifr.ip_ifr_flags, IP_IFF_UP); if (ipcom_socketioctl(fd, IP_SIOCSIFFLAGS, &ifr) < 0) { printf("ifconfig: failed to set interface flags"); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } ((struct Ip_sockaddr_in *)&ifr.ip_ifr_addr)->sin_family = IP_AF_INET; ((struct Ip_sockaddr_in *)&ifr.ip_ifr_addr)->sin_len = sizeof(struct Ip_sockaddr_in); ((struct Ip_sockaddr_in *)&ifr.ip_ifr_addr)->sin_addr.s_addr = ipcom_inet_addr(pAddr); /* Set IP address */ if (ipcom_socketioctl(fd, IP_SIOCSIFADDR, &ifr) == IP_SOCKERR) { printf("Failed to set address for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } ((struct Ip_sockaddr_in *)&ifr.ip_ifr_addr)->sin_addr.s_addr = (Ip_u32)ip_htonl(mask); /* Set subnet mask. */ if (ipcom_socketioctl(fd, IP_SIOCSIFNETMASK, &ifr) == IP_SOCKERR) { printf("Failed to set subnet mask for %s, errno %d\n", mirrorDevName, ipcom_errno); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } #if 0 if (ifMaskSet (mirrorDevName, mask) != OK) { printf("ifMaskSet failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } if (ifAddrSet (mirrorDevName, pAddr) != OK) { printf("ifAddrSet failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } #endif #ifdef INET6 } if (gotAddrv6) { struct Ip_in6_addr inaddr6; struct Ip_in6_aliasreq ifareq6; int i; if (ip6Attach (MIRROR_STACK_UNIT_NUM, MIRROR_DEV_NAME) != OK) { printf("ip6Attach failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } fd = ipcom_socket(IP_AF_INET6, IP_SOCK_DGRAM, 0); if (fd == IP_INVALID_SOCKET) { printf("Failed to open a socket\n"); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } memset(&ifareq6, 0, sizeof(struct Ip_in6_aliasreq)); strcpy(ifareq6.ifra_name, ipcom_get_ip_if_name(mirrorDevName)); if (ipcom_inet_pton(IP_AF_INET6, pAddrv6, &inaddr6) <= 0) { printf("Failed to convert an IPv6 address\n"); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } ifareq6.ifra_addr.sin6_addr = inaddr6; ifareq6.ifra_addr.sin6_family = IP_AF_INET6; ifareq6.ifra_addr.sin6_len = sizeof(struct Ip_sockaddr_in6); if (IP_IN6_IS_ADDR_LINK_LOCAL(&inaddr6)) ifareq6.ifra_addr.sin6_scope_id = ipcom_if_nametoindex(ifareq6.ifra_name); ifareq6.ifra_prefixmask.sin6_family = IP_AF_INET6; ifareq6.ifra_prefixmask.sin6_len = sizeof(struct Ip_sockaddr_in6); for (i = 0; i < prefixLen; i++) { IP_BIT_SET(((Ip_u16*) &ifareq6.ifra_prefixmask.sin6_addr)[i / 16], ip_htons(0x8000 >> (i % 16))); } /* Set lifetimes */ ifareq6.ifra_lifetime.ia6t_preferred = (long)IPCOM_ADDR_INFINITE; ifareq6.ifra_lifetime.ia6t_expire = (long)IPCOM_ADDR_INFINITE; /* Sanity */ ifareq6.ifra_flags = IP_IN6_IFF_TENTATIVE; /* Add IPv6 address */ if (ipcom_socketioctl(fd, IP_SIOCAIFADDR_IN6, &ifareq6) == IP_SOCKERR) { printf("Failed to add IPv6 address for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } #if 0 if (ifFlagChange (mirrorDevName, IFF_INET6_UP, TRUE) != OK) { printf("ifFlagChange (IFF_INET6_UP) failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } if (if6AddrAdd (mirrorDevName, pAddrv6, prefixLen, 0) != OK) { printf("if6AddrAdd failed for %s\n", mirrorDevName); muxDevUnload (MIRROR_DEV_NAME, MIRROR_STACK_UNIT_NUM); return ERROR; } #endif } #endif /* INET6 */ /* Load the bridge side of the mirror END driver */ pMuxCookie = muxDevLoad (MIRROR_BRIDGE_UNIT_NUM, mirrorEndLoad, MIRROR_LOAD_STRING, FALSE, NULL); if (pMuxCookie == NULL) { printf("muxDevLoad failed for %s%d\n", MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM); return ERROR; } if (muxDevStart(pMuxCookie) != OK) { muxDevUnload (MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM); printf ("muxDevStart failed for %s%d\n", MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM); return ERROR; } /* Set the bridge side driver to promiscuous mode */ pEnd = PDEVCOOKIE_TO_ENDOBJ(pMuxCookie); devicePromiscuousModeSet(pEnd); /* Add this mirror port to the bridge */ if (bridgePortAdd (MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM) != OK) { printf ("bridgePortAdd failed for %s%d\n", MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM); muxDevStop (pMuxCookie); muxDevUnload (MIRROR_DEV_NAME, MIRROR_BRIDGE_UNIT_NUM); return ERROR; } return OK; } /******************************************************************************* * * promiscuousModeSet - Change mode to promiscuous * * This routine sets the specified interface to promiscuous mode using the * the driver's ioctl call. * * RETURNS: OK or ERROR if fail * * NOMANUAL */ STATUS promiscuousModeSet ( char * pEndName, /* name of device */ int unit /* unit number of device */ ) { END_OBJ * pEnd; pEnd = endFindByName(pEndName,unit); if (pEnd == NULL) { printf("%s%d: Device does not exist or its driver is not loaded\n", pEndName, unit); return ERROR; } devicePromiscuousModeSet(pEnd); return OK; } /***************************************************************************** * * devicePromiscuousModeSet - Turn on hardware device's promiscuous mode * */ LOCAL void devicePromiscuousModeSet ( END_OBJ * pEnd /* end object */ ) { int ifFlags = 0; /* get the current interface flag settings */ if (pEnd->pFuncTable->ioctl != NULL) pEnd->pFuncTable->ioctl (pEnd, (int)EIOCGFLAGS, (void *)&ifFlags); ifFlags |= IP_IFF_PROMISC; * the driver won't perform the actual action of setting the device to the * promiscuous mode if this flag is not set. */ ifFlags |= IP_IFF_UP; if (pEnd->pFuncTable->ioctl != NULL) pEnd->pFuncTable->ioctl (pEnd, (int)EIOCSFLAGS, (void *)ifFlags); } #ifdef INCLUDE_WDB #if ((WDB_COMM_TYPE == WDB_COMM_END || defined(INCLUDE_WDB_COMM_END)) && \ !defined(WDB_END_DEVICE_NAME) && !defined(WDB_END_DEVICE_UNIT)) /***************************************************************************** * * bridgeWdbEndEntryFind - Find the WDB END interface * */ LOCAL STATUS bridgeWdbEndEntryFind ( BRIDGE_NODE * pGetEntry ) { END_TBL_ENTRY * pDevTbl; char devName[END_NAME_MAX + 1]; for (pDevTbl = endDevTbl; pDevTbl->endLoadFunc != NULL; pDevTbl++) { /* get the name of the device by passing argument devName = '\0' */ bzero (devName, END_NAME_MAX + 1); if (pDevTbl->endLoadFunc(devName, NULL) != 0) return (ERROR); /* compare the name of the device to the boot device selected */ if (strncmp (sysBootParams.bootDev, (const char *) devName, strlen((const char *) devName)) == 0) { /* Verify that the device unit number matches */ if (pDevTbl->unit == sysBootParams.unitNum) break; } } /* if no END Device found, default to first valid table entry */ if (pDevTbl->endLoadFunc == NULL) { if (endDevTbl->endLoadFunc == NULL) return (ERROR); else pDevTbl = endDevTbl; } pGetEntry->unit = pDevTbl->unit; pDevTbl->endLoadFunc(pGetEntry->devName, NULL); return OK; } /***************************************************************************** * * bridgeEndTblRestore - Restore the endDevTbl when WDB task is created * */ LOCAL void bridgeEndTblRestore ( WIND_TCB * pNewTcb ) { /* restore back the endTbl entry */ #if (defined(_WRS_VXWORKS_MAJOR) && (_WRS_VXWORKS_MAJOR >= 6)) /* VxW 6.x */ if (strcmp(pNewTcb->objCore.name,"tWdbTask") == 0) #else if (strcmp(pNewTcb->name,"tWdbTask") == 0) #endif { /* the WDB task has been created, restore back the endTbl */ bcopy((char *)pSavedEndTbl, (char *)endDevTbl, savedTblEntries * sizeof(END_TBL_ENTRY)); free((void *)pSavedEndTbl); taskCreateHookDelete((FUNCPTR)bridgeEndTblRestore); } } #endif #endif
31.452156
110
0.583999
[ "object" ]
8d4c8a1d2951a3605f6d6b324871c83458dabd5a
1,947
h
C
directfire_github/trunk/android_prebuild/libcommon/include/map/mapmetainfo.h
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
1
2015-08-12T04:05:33.000Z
2015-08-12T04:05:33.000Z
directfire_github/trunk/android_prebuild/libcommon/include/map/mapmetainfo.h
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
null
null
null
directfire_github/trunk/android_prebuild/libcommon/include/map/mapmetainfo.h
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
null
null
null
#ifndef MAPMETAINFO_H #define MAPMETAINFO_H #include <iostream> #include <vector> using namespace std; #include "mapsceneinfo.h" class MapMetaInfo { public: MapMetaInfo(); ~MapMetaInfo(); void dumpInfo(); void setMaxPlayers(int count){m_maxPlayers = count;} int maxPlayers() {return m_maxPlayers;} void setMaxTeams(int count){m_maxTeams = count;} int maxTeams() {return m_maxTeams;} void setMapSizeW(int w){m_mapSizeW = w;} int mapSizeW() {return m_mapSizeW;} void setMapSizeH(int h){m_mapSizeH = h;} int mapSizeH() {return m_mapSizeH;} void setGateId(const string& id){m_gateId = id;} const string& gateId(){return m_gateId;} void setGateName(const string& name){m_gateName = name;} const string& gateName(){return m_gateName;} const string& gateFileName(){return m_gateFileName;} void setGateFileName(const string& file){m_gateFileName = file;} const string& pathFileName(){return m_pathFileName;} void setPathFileName(const string& file){m_pathFileName = file;} const string& mapShotPath(){return m_mapShotPath;} void setMapShotPath(const string& file){m_mapShotPath = file;} void setAllScene(vector<MapSceneInfo>& scene) {m_allScene = scene;} vector<MapSceneInfo>& allScene() {return m_allScene;} void setStaticScene(vector<MapSceneInfo>& scene) {m_staticScene = scene;} vector<MapSceneInfo>& staticScene() {return m_staticScene;} void setDynamicScene(vector<MapSceneInfo>& scene) {m_dynamicScene = scene;} vector<MapSceneInfo>& dynamicScene() {return m_dynamicScene;} private: int m_maxPlayers; int m_maxTeams; int m_mapSizeW; int m_mapSizeH; string m_gateId; string m_gateName; string m_gateFileName; string m_pathFileName; string m_mapShotPath; vector<MapSceneInfo> m_allScene; vector<MapSceneInfo> m_staticScene; vector<MapSceneInfo> m_dynamicScene; }; #endif // MAPMETAINFO_H
33.568966
79
0.724191
[ "vector" ]
8d504cc976d03d173ecce3e2a2258a5a50d3bca6
9,081
h
C
aws-cpp-sdk-lakeformation/include/aws/lakeformation/model/SearchDatabasesByLFTagsRequest.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-lakeformation/include/aws/lakeformation/model/SearchDatabasesByLFTagsRequest.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-lakeformation/include/aws/lakeformation/model/SearchDatabasesByLFTagsRequest.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lakeformation/LakeFormation_EXPORTS.h> #include <aws/lakeformation/LakeFormationRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/lakeformation/model/LFTag.h> #include <utility> namespace Aws { namespace LakeFormation { namespace Model { /** */ class AWS_LAKEFORMATION_API SearchDatabasesByLFTagsRequest : public LakeFormationRequest { public: SearchDatabasesByLFTagsRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "SearchDatabasesByLFTags"; } Aws::String SerializePayload() const override; /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; } /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); } /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline SearchDatabasesByLFTagsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline SearchDatabasesByLFTagsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;} /** * <p>A continuation token, if this is not the first call to retrieve this * list.</p> */ inline SearchDatabasesByLFTagsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} /** * <p>The maximum number of results to return.</p> */ inline int GetMaxResults() const{ return m_maxResults; } /** * <p>The maximum number of results to return.</p> */ inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; } /** * <p>The maximum number of results to return.</p> */ inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; } /** * <p>The maximum number of results to return.</p> */ inline SearchDatabasesByLFTagsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;} /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline const Aws::String& GetCatalogId() const{ return m_catalogId; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline bool CatalogIdHasBeenSet() const { return m_catalogIdHasBeenSet; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline void SetCatalogId(const Aws::String& value) { m_catalogIdHasBeenSet = true; m_catalogId = value; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline void SetCatalogId(Aws::String&& value) { m_catalogIdHasBeenSet = true; m_catalogId = std::move(value); } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline void SetCatalogId(const char* value) { m_catalogIdHasBeenSet = true; m_catalogId.assign(value); } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline SearchDatabasesByLFTagsRequest& WithCatalogId(const Aws::String& value) { SetCatalogId(value); return *this;} /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline SearchDatabasesByLFTagsRequest& WithCatalogId(Aws::String&& value) { SetCatalogId(std::move(value)); return *this;} /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your Lake Formation * environment. </p> */ inline SearchDatabasesByLFTagsRequest& WithCatalogId(const char* value) { SetCatalogId(value); return *this;} /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline const Aws::Vector<LFTag>& GetExpression() const{ return m_expression; } /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline bool ExpressionHasBeenSet() const { return m_expressionHasBeenSet; } /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline void SetExpression(const Aws::Vector<LFTag>& value) { m_expressionHasBeenSet = true; m_expression = value; } /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline void SetExpression(Aws::Vector<LFTag>&& value) { m_expressionHasBeenSet = true; m_expression = std::move(value); } /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline SearchDatabasesByLFTagsRequest& WithExpression(const Aws::Vector<LFTag>& value) { SetExpression(value); return *this;} /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline SearchDatabasesByLFTagsRequest& WithExpression(Aws::Vector<LFTag>&& value) { SetExpression(std::move(value)); return *this;} /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline SearchDatabasesByLFTagsRequest& AddExpression(const LFTag& value) { m_expressionHasBeenSet = true; m_expression.push_back(value); return *this; } /** * <p>A list of conditions (<code>LFTag</code> structures) to search for in * database resources.</p> */ inline SearchDatabasesByLFTagsRequest& AddExpression(LFTag&& value) { m_expressionHasBeenSet = true; m_expression.push_back(std::move(value)); return *this; } private: Aws::String m_nextToken; bool m_nextTokenHasBeenSet; int m_maxResults; bool m_maxResultsHasBeenSet; Aws::String m_catalogId; bool m_catalogIdHasBeenSet; Aws::Vector<LFTag> m_expression; bool m_expressionHasBeenSet; }; } // namespace Model } // namespace LakeFormation } // namespace Aws
38.155462
162
0.686488
[ "vector", "model" ]
8d600a634bc90f3e1aec0a00a0f70c00f23f40cc
39,182
c
C
eurasia/codegen/ffgen/reg.c
shaqfu786/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
3
2020-03-13T23:37:00.000Z
2021-09-03T06:34:04.000Z
eurasia/codegen/ffgen/reg.c
zzpianoman/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
null
null
null
eurasia/codegen/ffgen/reg.c
zzpianoman/GFX_Linux_DDK
f184ac914561fa100a5c92a488df777de8785f93
[ "FSFAP" ]
6
2015-02-05T03:01:01.000Z
2021-07-24T01:07:18.000Z
/****************************************************************************** * Name : reg.c * Author : James McCarthy * Created : 16/11/2005 * * Copyright : 2005-2008 by Imagination Technologies Limited. * : All rights reserved. No part of this software, either * : material or conceptual may be copied or distributed, * : transmitted, transcribed, stored in a retrieval system or * : translated into any human or computer language in any form * : by any means, electronic, mechanical, manual or otherwise, * : or disclosed to third parties without the express written * : permission of Imagination Technologies Limited, * : Home Park Estate, Kings Langley, Hertfordshire, * : WD4 8LZ, U.K. * * Platform : ANSI * * Modifications:- * $Log: reg.c $ *****************************************************************************/ #include <stdio.h> #include <math.h> #include "apidefs.h" #include "codegen.h" #include "macros.h" #include "source.h" #include "inst.h" #include "reg.h" /****************************************************************************** * Function Name: AddRegToList * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ static FFGenRegList *AddRegToList(FFGenCode *psFFGenCode, FFGenRegList *psRegList, FFGenReg *psRegToAdd, IMG_BOOL bCreateCopy, IMG_UINT32 uLineNumber, const IMG_CHAR *pszFileName) { FFGenRegList *psNewEntry; FFGenReg *psReg; FFGenRegList *psList = psRegList; PVR_UNREFERENCED_PARAMETER(psFFGenCode); PVR_UNREFERENCED_PARAMETER(uLineNumber); PVR_UNREFERENCED_PARAMETER(pszFileName); if (bCreateCopy) { /* Create copy of reg */ psReg = FFGENMalloc2(psFFGenCode->psFFGenContext, sizeof(FFGenReg), uLineNumber, pszFileName); *psReg = *psRegToAdd; } else { psReg = psRegToAdd; } if (psList) { /* Go to end of list */ while (psList->psNext) { psList = psList->psNext; } } #if defined(OGLES1_MODULE) && defined(FFGEN_UNIFLEX) psReg->pui32SrcOffset = IMG_NULL; psReg->pui32DstOffset = IMG_NULL; #endif /* defined(OGLES1_MODULE) && defined(FFGEN_UNIFLEX) */ /* Create new list entry */ psNewEntry = FFGENMalloc2(psFFGenCode->psFFGenContext, sizeof(FFGenRegList), uLineNumber, pszFileName); /* Add register to list entry */ psNewEntry->psReg = psReg; psNewEntry->psPrev = psList; psNewEntry->psNext = IMG_NULL; if (psList) { psList->psNext = psNewEntry; } else { psRegList = psNewEntry; } return psRegList; } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ static IMG_VOID CompressFreeList(FFGenCode *psFFGenCode) { FFGenRegList *psFreeList = psFFGenCode->psFreeTempList; IMG_BOOL bCompressed = IMG_TRUE; while (bCompressed) { bCompressed = IMG_FALSE; /* Search through list */ while (psFreeList) { FFGenRegList *psNext = psFreeList->psNext; FFGenReg *psReg = psFreeList->psReg; /* Is this reg at the end of the currently allocated space? */ if (psReg->uOffset + psReg->uSizeInDWords == psFFGenCode->uCurrentTempSize) { /* Remove it from the list and reduce the allocation size */ psFFGenCode->uCurrentTempSize -= psReg->uSizeInDWords; /* Remove entry */ if (psFreeList->psPrev) { psFreeList->psPrev->psNext = psNext; } if (psNext) { psNext->psPrev = psFreeList->psPrev; } /* If this entry is at the head of the list replace the head pointer */ if (psFreeList == psFFGenCode->psFreeTempList) { psFFGenCode->psFreeTempList = psNext; } FFGENFree(psFFGenCode->psFFGenContext, psReg); FFGENFree(psFFGenCode->psFFGenContext, psFreeList); bCompressed = IMG_TRUE; } else if (psNext) { FFGenReg *psNextReg = psNext->psReg; /* Can we merge these two together? */ if (psReg->uOffset + psReg->uSizeInDWords == psNextReg->uOffset) { psReg->uSizeInDWords += psNextReg->uSizeInDWords; /* remove it from the list */ psFreeList->psNext = psNext->psNext; if (psFreeList->psNext) { psFreeList->psNext->psPrev = psFreeList; } /* free the next reg */ FFGENFree(psFFGenCode->psFFGenContext, psNextReg); FFGENFree(psFFGenCode->psFFGenContext, psNext); psNext = psFreeList->psNext; bCompressed = IMG_TRUE; } /* Can we merge them the other way round? */ else if (psNextReg->uOffset + psNextReg->uSizeInDWords == psReg->uOffset) { psReg->uOffset = psNextReg->uOffset; psReg->uSizeInDWords += psNextReg->uSizeInDWords; /* free the next reg */ FFGENFree(psFFGenCode->psFFGenContext, psNextReg); /* remove it from the list */ psFreeList->psNext = psNext->psNext; if (psFreeList->psNext) { psFreeList->psNext->psPrev = psFreeList; } FFGENFree(psFFGenCode->psFFGenContext, psNext); psNext = psFreeList->psNext; bCompressed = IMG_TRUE; } } /* Get next temp on list */ psFreeList = psNext; } } } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ IMG_INTERNAL IMG_VOID ReleaseReg(FFGenCode *psFFGenCode, FFGenReg *psReg) { if (!psReg) { return; } /* Can only add temps back to a free list */ if (psReg->eType != USEASM_REGTYPE_TEMP) { return; } /* Was this the last temp allocated? */ if (psReg->uOffset + psReg->uSizeInDWords == psFFGenCode->uCurrentTempSize) { /* Yes, then just free it and reduce the size of the temp stack This reduces the chance of having awkward size holes (like a matrix) in our free temp list if we're careful about the order in which we make and release large temp allocations */ psFFGenCode->uCurrentTempSize -= psReg->uSizeInDWords; /* free it */ FFGENFree(psFFGenCode->psFFGenContext, psReg); } else { /* Add this temp back to the free list */ psFFGenCode->psFreeTempList = AddRegToList(psFFGenCode, psFFGenCode->psFreeTempList, psReg, IMG_FALSE, __LINE__, __FILE__); CompressFreeList(psFFGenCode); } #if 0 { FFGenRegList *psList = psFFGenCode->psFreeTempList; IMG_UINT32 uTotal = 0; COMMENT(psFFGenCode, "Temp size = %d", psFFGenCode->uCurrentTempSize); while (psList) { COMMENT(psFFGenCode, "Temp reg = (%d->%d) %d", psList->psReg->uOffset, psList->psReg->uOffset + psList->psReg->uSizeInDWords, psList->psReg->uSizeInDWords); uTotal += psList->psReg->uSizeInDWords; psList = psList->psNext; } COMMENT(psFFGenCode, "Total = %d", uTotal); } #endif } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ static FFGenReg *GetTemp(FFGenCode *psFFGenCode, IMG_UINT32 uSize, IMG_UINT32 uLineNumber, const IMG_CHAR *pszFileName) { /* Get pointer to temp list */ FFGenRegList *psFreeList = psFFGenCode->psFreeTempList; FFGenReg *psRetReg = IMG_NULL; PVR_UNREFERENCED_PARAMETER(uLineNumber); PVR_UNREFERENCED_PARAMETER(pszFileName); /* Any free regs available */ while(psFreeList) { /* Do the sizes match */ if (psFreeList->psReg->uSizeInDWords == uSize) { /* return this register */ psRetReg = psFreeList->psReg; /* remove from free list */ if (psFreeList->psNext) { psFreeList->psNext->psPrev = psFreeList->psPrev; } if (psFreeList->psPrev) { psFreeList->psPrev->psNext = psFreeList->psNext; } /* Are we removing the head entry? */ if (psFreeList == psFFGenCode->psFreeTempList) { psFFGenCode->psFreeTempList = psFreeList->psNext; } /* remove this entry */ FFGENFree(psFFGenCode->psFFGenContext, psFreeList); return psRetReg; } else if (psFreeList->psReg->uSizeInDWords > uSize) { /* Create a new reg */ psRetReg = FFGENMalloc2(psFFGenCode->psFFGenContext, sizeof(FFGenReg), uLineNumber, pszFileName); *psRetReg = *(psFreeList->psReg); psRetReg->uSizeInDWords = uSize; /* Adjust current record */ psFreeList->psReg->uSizeInDWords = psFreeList->psReg->uSizeInDWords - uSize; psFreeList->psReg->uOffset += uSize; return psRetReg; } /* Get next temp on list */ psFreeList = psFreeList->psNext; } /* No free temp found so create a new one */ psRetReg = FFGENMalloc2(psFFGenCode->psFFGenContext, sizeof(FFGenReg), uLineNumber, pszFileName); /* Setup reg */ psRetReg->eType = USEASM_REGTYPE_TEMP; psRetReg->uSizeInDWords = uSize; psRetReg->uOffset = psFFGenCode->uCurrentTempSize; psRetReg->eBindingRegDesc = 0; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of temp allocs */ psFFGenCode->uCurrentTempSize += uSize; /* Store maximum temp size */ if (psFFGenCode->uCurrentTempSize > psFFGenCode->uTempSize) { psFFGenCode->uTempSize = psFFGenCode->uCurrentTempSize; } return psRetReg; } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ static IMG_BOOL LoadStoreConstant(FFGenCode *psFFGenCode, IMG_BOOL bLoad, FFGenReg *psConstReg, IMG_UINT32 uSizeInDWords, IMG_UINT32 uOffsetInDWords, FFGENIndexReg *psIndexReg, FFGenReg *psLoadDestStoreSrcReg, /* Dest for load, src for store */ const IMG_CHAR *pszDesc, IMG_BOOL bFCLFillLoad, IMG_BOOL bIssueWDF, IMG_UINT32 uLineNumber, const IMG_CHAR *pszFileName) { FFGenReg *psTemp = psLoadDestStoreSrcReg; FFGenInstruction *psInst = &(psFFGenCode->sInstruction); FFGenReg *psSABaseAddress = &(psFFGenCode->sSAConstBaseAddress); FFGenReg *psImmediateIntReg = &(psFFGenCode->sImmediateIntReg); FFGenReg *psImmediateIntReg2 = &(psFFGenCode->sImmediateIntReg2); IMG_UINT32 uDataSizeInDWords = uSizeInDWords; /* Integer because it might be negative */ IMG_INT32 iDataOffsetInBytes = (((psConstReg->uOffset + uOffsetInDWords) * sizeof(IMG_UINT32)) - psFFGenCode->iSAConstBaseAddressAdjust); IMG_INT32 iDataOffsetInDWords = iDataOffsetInBytes / sizeof(IMG_UINT32); if (!uSizeInDWords) { psFFGenCode->psFFGenContext->pfnPrint("LoadConstant(): No data to load\n"); } if (iDataOffsetInBytes < 0) { psFFGenCode->psFFGenContext->pfnPrint("LoadConstant(): Can't handle negative values\n"); } if(bLoad) { /* Setup register */ psTemp->eBindingRegDesc = psConstReg->eBindingRegDesc; psTemp->eWDFStatus = 0; psTemp->uIndex = USEREG_INDEX_NONE; if (pszDesc) { COMMENT(psFFGenCode, "Load the %s from memory", pszDesc); } } else { if(pszDesc) { COMMENT(psFFGenCode, "Store the %s to memory", pszDesc); } } /* More optimal method that avoids the need for the address calculation Non incremental = Pre Increment with out the writeback of the address */ /* Can we do a non incremental load? */ if (!psIndexReg && (uDataSizeInDWords <= 16) && (iDataOffsetInDWords < EURASIA_USE_LDST_MAX_IMM_ABSOLUTE_OFFSET) && (iDataOffsetInDWords >= 1)) { /* Take off 4bytes (1 Dword) to compensate for preincrement */ psImmediateIntReg->uOffset = iDataOffsetInDWords - 1; if(bLoad) { /* Get free DRC channel */ psFFGenCode->sDRCReg.uOffset = GetDRC(psFFGenCode); /* Supply fetch count intead of repeat count */ SET_FETCH_COUNT(uDataSizeInDWords); if(bFCLFillLoad) { SET_FORCE_CACHELINEFILL_LOAD(); } /* ldad.f<uSizeInDwords> r[Const], [ r[addressreg], #(offset) ], DRC<DRCChannel> */ INST4(LDAD, psTemp, psSABaseAddress, psImmediateIntReg, &(psFFGenCode->sRangeReg), &(psFFGenCode->sDRCReg), IMG_NULL); if(bIssueWDF) { /* Issue data fence - this needs optimising */ INST0(WDF, &(psFFGenCode->sDRCReg), IMG_NULL); /* Mark data channel is not outstanding anymore */ psFFGenCode->abOutstandingDRC[psFFGenCode->sDRCReg.uOffset] = IMG_FALSE; } } else { IMG_UINT32 i, uBaseOffset = psImmediateIntReg->uOffset; psFFGenCode->sDRCReg.uOffset = GetDRC(psFFGenCode); for(i = 0; i < uDataSizeInDWords; i++) { SET_FETCH_COUNT(1); SET_INT_VALUE(psImmediateIntReg, uBaseOffset + i); SETSRCOFF(1, i); INST2(STAD, psSABaseAddress, psImmediateIntReg, psTemp, IMG_NULL); } /* Issue data fence */ psImmediateIntReg->uOffset = EURASIA_USE1_IDF_PATH_ST; INST1(IDF, &(psFFGenCode->sDRCReg), psImmediateIntReg, IMG_NULL); if(bIssueWDF) { /* Issue data fence - this needs optimising */ INST0(WDF, &(psFFGenCode->sDRCReg), IMG_NULL); /* Mark data channel is not outstanding anymore */ psFFGenCode->abOutstandingDRC[psFFGenCode->sDRCReg.uOffset] = IMG_FALSE; } } } else { /* Get temp for address calc */ FFGenReg *psAddress = GetTemp(psFFGenCode, 1, uLineNumber, pszFileName); /* Check reg succeeded */ if (!psAddress) { psFFGenCode->psFFGenContext->pfnPrint("Failed to alloc address reg\n"); return IMG_FALSE; } if (psIndexReg) { IMG_UINT32 uStride; /* Work out stride */ if (!psIndexReg->uStrideInDWords) { uStride = uSizeInDWords * sizeof(IMG_UINT32); } else { uStride = psIndexReg->uStrideInDWords * sizeof(IMG_UINT32); } /* Straightforward load? */ if (uStride < 64) { /* Set up immediate value with size of item in bytes */ psImmediateIntReg2->uOffset = uStride; /* Add in index register offset */ if (psIndexReg->uIndexRegOffset) { SETSRCOFF(0, psIndexReg->uIndexRegOffset); } /* Multiply index by size of item */ INST2(IMULU16, psAddress, psIndexReg->psReg, psImmediateIntReg2, IMG_NULL); if (psIndexReg->uIndexRegFlags) { /* Add flags to index register */ SETSRCFLAG(0, psIndexReg->uIndexRegFlags); } /* iadd32 r[addressreg], r[indexReg].l/h, sa[constbaseaddress] */ INST2(IADD32, psAddress, psAddress, psSABaseAddress, IMG_NULL); } /* Shift to get value */ else if (IS_POWER_OF_2(uStride)) { /* Calculate how much to shift value by +0.5f to get round precision errors */ IMG_UINT32 uShift = (IMG_UINT32)(log(uStride)/log(2) + 0.5f); /* Set up immediate value with shift value */ psImmediateIntReg2->uOffset = uShift; /* Add in index register offset */ if (psIndexReg->uIndexRegOffset) { SETSRCOFF(0, psIndexReg->uIndexRegOffset); } /* Left shift the index register by the value */ INST2(SHL, psAddress, psIndexReg->psReg, psImmediateIntReg2, IMG_NULL); if (psIndexReg->uIndexRegFlags) { /* Add flags to index register */ SETSRCFLAG(0, psIndexReg->uIndexRegFlags); } /* iadd32 r[addressreg], r[indexReg].l/h, sa[constbaseaddress] */ INST2(IADD32, psAddress, psAddress, psSABaseAddress, IMG_NULL); } else { psFFGenCode->psFFGenContext->pfnPrint("This load size currently not supported\n"); return IMG_FALSE; } /* Does the offset need loading */ if (iDataOffsetInDWords >= EURASIA_USE_LDST_MAX_IMM_ABSOLUTE_OFFSET) { /* Get a temp to put the constant into */ FFGenReg *psOffsetTemp = GetTemp(psFFGenCode, 1, uLineNumber, pszFileName); /* Check reg succeeded */ if (!psOffsetTemp) { psFFGenCode->psFFGenContext->pfnPrint("Failed to alloc offset reg \n"); return IMG_FALSE; } /* Setup immediate value with data offset */ psImmediateIntReg->uOffset = (IMG_UINT32)iDataOffsetInBytes; /* Move constant off set into temp - mov r[addressreg], #constant_offset */ INST1(LIMM, psOffsetTemp, psImmediateIntReg, IMG_NULL); /* Add the constant offset into the secondary base address register */ SETSRCFLAG(0, USEASM_ARGFLAGS_LOW); /* iadd32 r[addressreg], r[addressreg].l, sa[constbaseaddress] */ INST2(IADD32, psAddress, psOffsetTemp, psAddress, IMG_NULL); /* Free up offset reg */ ReleaseReg(psFFGenCode, psOffsetTemp); /* Data offset has now been used */ iDataOffsetInBytes = 0; iDataOffsetInDWords = 0; } } else { /* Do we need to do the addition */ if (iDataOffsetInDWords < EURASIA_USE_LDST_MAX_IMM_ABSOLUTE_OFFSET) { INST1(MOV, psAddress, psSABaseAddress, IMG_NULL); } else { /* Setup immediate value */ psImmediateIntReg->uOffset = (IMG_UINT32)iDataOffsetInBytes; /* Move constant off set into temp - mov r[addressreg], #constant_offset */ INST1(LIMM, psAddress, psImmediateIntReg, IMG_NULL); /* Add the constant offset into the secondary base address register */ SETSRCFLAG(0, USEASM_ARGFLAGS_LOW); /* iadd32 r[addressreg], r[addressreg].l, sa[constbaseaddress] */ INST2(IADD32, psAddress, psAddress, psSABaseAddress, IMG_NULL); /* Data offset has now been used */ iDataOffsetInBytes = 0; iDataOffsetInDWords = 0; } } /* Max load count is 16 so need to break into chunks if larger */ while (uDataSizeInDWords) { IMG_UINT32 uFetchCount; /* Calc off set for data loads */ IMG_UINT32 uDestOffset = uSizeInDWords - uDataSizeInDWords; uFetchCount = uDataSizeInDWords; /* Max fetch is 16 */ if (uFetchCount > 16) { uFetchCount = 16; } /* update amount of data fetched */ uDataSizeInDWords -= uFetchCount; SET_POST_INCREMENTAL_LOADSTORE(); psImmediateIntReg->uOffset = iDataOffsetInDWords; SETDESTOFF(uDestOffset); if(bLoad) { /* Get free DRC channel */ psFFGenCode->sDRCReg.uOffset = GetDRC(psFFGenCode); SET_REPEAT_COUNT(uFetchCount); /* ldad.f<uSizeInDwords> r[Const], [ r[addressreg], #0++ ], DRC<DRCChannel> */ if(bFCLFillLoad) { SET_FORCE_CACHELINEFILL_LOAD(); } INST4(LDAD, psTemp, psAddress, psImmediateIntReg, &(psFFGenCode->sRangeReg), &(psFFGenCode->sDRCReg), IMG_NULL); if(bIssueWDF) { /* Issue data fence - this needs optimising */ INST0(WDF, &(psFFGenCode->sDRCReg), IMG_NULL); /* Mark data channel is not outstanding anymore */ psFFGenCode->abOutstandingDRC[psFFGenCode->sDRCReg.uOffset] = IMG_FALSE; } } else { IMG_UINT32 i; /* Get free DRC channel */ psFFGenCode->sDRCReg.uOffset = GetDRC(psFFGenCode); for(i = 0; i < uFetchCount; i++) { SET_REPEAT_COUNT(1); SETSRCOFF(1, i); /* stad [Base, #offset++], r[] */ INST2(STAD, psSABaseAddress, psImmediateIntReg, psTemp, IMG_NULL); } /* Issue data fence - this needs optimising */ psImmediateIntReg->uOffset = EURASIA_USE1_IDF_PATH_ST; INST1(IDF, &(psFFGenCode->sDRCReg), psImmediateIntReg, IMG_NULL); if(bIssueWDF) { /* Issue data fence - this needs optimising */ INST0(WDF, &(psFFGenCode->sDRCReg), IMG_NULL); /* Mark data channel is not outstanding anymore */ psFFGenCode->abOutstandingDRC[psFFGenCode->sDRCReg.uOffset] = IMG_FALSE; } } } /* Free up address reg */ ReleaseReg(psFFGenCode, psAddress); } return IMG_TRUE; } static FFGenReg *LoadConstant(FFGenCode *psFFGenCode, FFGenReg *psConstReg, IMG_UINT32 uSizeInDWords, IMG_UINT32 uLoadOffsetInDWords, FFGENIndexReg *psIndexReg, const IMG_CHAR *pszDesc, IMG_BOOL bFCLFillLoad, IMG_UINT32 uLineNumber, const IMG_CHAR *pszFileName) { /* Get a temp to put the constant into */ FFGenReg *psTemp = GetTemp(psFFGenCode, uSizeInDWords, uLineNumber, pszFileName); /* Check reg succeeded */ if (!psTemp) { psFFGenCode->psFFGenContext->pfnPrint("Failed to alloc const reg\n"); return IMG_NULL; } LoadStoreConstant(psFFGenCode, IMG_TRUE, psConstReg, uSizeInDWords, uLoadOffsetInDWords, psIndexReg, psTemp, pszDesc, bFCLFillLoad, IMG_TRUE, /* Issue WDF immediately - get data back immediately */ uLineNumber, pszFileName); return psTemp; } /****************************************************************************** * Function Name: RelativeAddressingSA * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : Sets up HW index register to allow relative addressing into * a secondary attribute array. *****************************************************************************/ static FFGenReg *RelativeAddressingSA(FFGenCode *psFFGenCode, FFGenReg *psReg, IMG_UINT32 uSize, FFGENIndexReg *psIndexReg, const IMG_CHAR *pszDesc, IMG_UINT32 uLineNumber, const IMG_CHAR *pszFileName) { FFGenInstruction *psInst = &(psFFGenCode->sInstruction); FFGenReg *psRetReg; FFGenReg *psImmediateIntReg = &(psFFGenCode->sImmediateIntReg); FFGenReg *psIntSrcSelReg = &psFFGenCode->sIntSrcSelReg; FFGenReg *psHWIndexReg = &psFFGenCode->sIndexLowReg; FFGenReg sIntSrc2SelReg = *psIntSrcSelReg; FFGenReg *psTemp; PVR_UNREFERENCED_PARAMETER(pszDesc); /* Get a temp to put the constant into */ psTemp = GetTemp(psFFGenCode, 1, uLineNumber, pszFileName); /* Check reg succeeded */ if (!psTemp) { psFFGenCode->psFFGenContext->pfnPrint("Failed to alloc const reg\n"); return IMG_NULL; } /* Alloc space for reg */ psRetReg = FFGENMalloc(psFFGenCode->psFFGenContext, sizeof(FFGenReg)); /* Check reg succeeded */ if (!psRetReg) { psFFGenCode->psFFGenContext->pfnPrint("Failed to malloc register\n"); return IMG_NULL; } /* Set temp to base of these indexable SAs */ psImmediateIntReg->uOffset = psReg->uOffset; /* Mark this instruction for index patching - in case we move the indexable secondaries at the end */ SET_INDEXPATCH(1); INST1(LIMM, psTemp, psImmediateIntReg, "mov input offset into temp"); SET_INDEXPATCH(0); /* Set src selection to U32 */ SET_INTSRCSEL(psIntSrcSelReg, USEASM_INTSRCSEL_U32); /* Set src2 selection to None */ SET_INTSRCSEL(&sIntSrc2SelReg, USEASM_INTSRCSEL_NONE); psImmediateIntReg->uOffset = psIndexReg->uStrideInDWords; /* Add in index register offset */ if (psIndexReg->uIndexRegOffset) { SETSRCOFF(0, psIndexReg->uIndexRegOffset); } /* Add in index register low/high */ if(psIndexReg->uIndexRegFlags == USEASM_ARGFLAGS_HIGH) { SETSRCFLAG(0, USEASM_ARGFLAGS_HIGH); } else { SETSRCFLAG(0, USEASM_ARGFLAGS_LOW); } /* HWIndex = SWindex.l/h * stride + temp */ INST6(IMAE, psHWIndexReg, psIndexReg->psReg, psImmediateIntReg, psTemp, psIntSrcSelReg, &sIntSrc2SelReg, &sIntSrc2SelReg, "input index * stride + offset"); psRetReg->eType = USEASM_REGTYPE_SECATTR; psRetReg->uOffset = 0; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = psReg->eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_L; /* add to throw away list */ psFFGenCode->psThrowAwayList = AddRegToList(psFFGenCode, psFFGenCode->psThrowAwayList, psRetReg, IMG_FALSE, uLineNumber, pszFileName); /* Free up temp reg */ ReleaseReg(psFFGenCode, psTemp); return psRetReg; } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : This function is horrible, probably need to split the constant stuff out *****************************************************************************/ IMG_INTERNAL FFGenReg *GetRegfn(FFGenCode *psFFGenCode, UseasmRegType eType, FFGenRegDesc eBindingRegDesc, IMG_UINT32 uLoadOffsetInDWords, FFGENIndexReg *psIndexReg, IMG_UINT32 uSize, IMG_CHAR *pszDesc, IMG_BOOL bAllocSpaceOnly, IMG_BOOL bIndexableSecondary, IMG_BOOL bFCLFillLoad, IMG_UINT32 uLineNumber, IMG_CHAR *pszFileName) { FFGenReg *psReg, *psRetReg = IMG_NULL; FFGenRegList **ppsList, *psList; IMG_UINT32 *puCurrentAllocSize = IMG_NULL; IMG_BOOL bConstantLoadRequired = IMG_FALSE; if (eType != USEASM_REGTYPE_SECATTR && uLoadOffsetInDWords) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Load offsets only valid for constants (%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } if (!uSize) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Size was 0 (%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } switch (eType) { case USEASM_REGTYPE_OUTPUT: puCurrentAllocSize = &(psFFGenCode->uOutputSize); ppsList = &(psFFGenCode->psOutputsList); break; case USEASM_REGTYPE_PRIMATTR: puCurrentAllocSize = &(psFFGenCode->uInputSize); ppsList = &(psFFGenCode->psInputsList); if(psFFGenCode->eCodeGenFlags & FFGENCGF_INPUT_REG_SIZE_4) { if (uSize != 4) { #if !defined(OGLES1_MODULE) /* This is benign in opengles - don't emit the error */ psFFGenCode->psFFGenContext->pfnPrint("GetReg: Only valid input register size for opengl is 4, automatically adjusting (%s, %d)\n", pszFileName, uLineNumber); #endif uSize = 4; } } break; case USEASM_REGTYPE_SECATTR: ppsList = &(psFFGenCode->psConstantsList); break; case USEASM_REGTYPE_TEMP: /* Get a free temp */ return GetTemp(psFFGenCode, uSize, uLineNumber, pszFileName); default: psFFGenCode->psFFGenContext->pfnPrint("GetReg: Invalid reg type (%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } /* Reset list */ psList = *ppsList; /* Search through input list to see if this has already been allocated */ while (psList && !psRetReg) { psReg = psList->psReg; /* Get next entry */ psList = psList->psNext; /* Does binding info match */ if (psReg->eBindingRegDesc == eBindingRegDesc) { /* Can't increase intial alloc */ if (uSize > psReg->uSizeInDWords) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Can't reget register with larger size than initial get or alloc (%s, %d)!\n", pszFileName, uLineNumber); return IMG_NULL; } /* Can't reserve same space twice */ if (bAllocSpaceOnly) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Can't alloc space for the same register twice\n"); return IMG_NULL; } /* Is this an exact match for the existing register? */ if (psReg->uSizeInDWords == uSize) { /* If we've found a match for a constant but the contents were stored in a temp then we can't rely on them still being there. Could improve this by addding some info to say if the contents of a temp still held the relavant constant info. */ if (eType == USEASM_REGTYPE_SECATTR && psReg->eType == USEASM_REGTYPE_TEMP) { if (uLoadOffsetInDWords || psIndexReg) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: If sizes match for existing constant reg then load offset and index reg should be 0\n"); return IMG_NULL; } return LoadConstant(psFFGenCode, psReg, uSize, uLoadOffsetInDWords, psIndexReg, pszDesc, bFCLFillLoad, uLineNumber, pszFileName); } else { return psReg; } } else { if (eType == USEASM_REGTYPE_SECATTR) { /* Check load offset won't take it out of range */ if (uLoadOffsetInDWords + uSize > psReg->uSizeInDWords) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Load offset + size (%d + %d = %d) exceeds size of original alloc (%d) (%s, %d)!\n", uSize, uLoadOffsetInDWords, uSize + uLoadOffsetInDWords, psReg->uSizeInDWords, pszFileName, uLineNumber); return IMG_NULL; } /* Do a partial load of this constant */ if (psReg->eType == USEASM_REGTYPE_TEMP) { return LoadConstant(psFFGenCode, psReg, uSize, uLoadOffsetInDWords, psIndexReg, pszDesc, bFCLFillLoad, uLineNumber, pszFileName); } /* Create a copy of an area from the original sec attr alloc, or use indexable sec attr */ else if (psReg->eType == USEASM_REGTYPE_SECATTR) { if (psIndexReg) { #ifdef FFGEN_UNIFLEX if(IF_FFGENCODE_UNIFLEX) { /* We are indexing a section of the palette. FFGEN_UNIFLEX uses the relative address register, so just return the whole palette. */ return psReg; } #endif return RelativeAddressingSA(psFFGenCode, psReg, uSize, psIndexReg, pszDesc, uLineNumber, pszFileName); } /* Alloc space for reg */ psRetReg = FFGENMalloc(psFFGenCode->psFFGenContext, sizeof(FFGenReg)); psRetReg->eType = USEASM_REGTYPE_SECATTR; psRetReg->uOffset = psReg->uOffset + uLoadOffsetInDWords; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* add to throw away list */ psFFGenCode->psThrowAwayList = AddRegToList(psFFGenCode, psFFGenCode->psThrowAwayList, psRetReg, IMG_FALSE, uLineNumber, pszFileName); return psRetReg; } } else { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Can only reget constants with a different size from original get/alloc (%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } } } } /* Check no offset has been set */ if (uLoadOffsetInDWords) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Load offsets not valid for 1st get/alloc (%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } if (psIndexReg) { psFFGenCode->psFFGenContext->pfnPrint("GetReg: Reg space must be reserved using AllocRegSpace() before a relative load can be executed(%s, %d)\n", pszFileName, uLineNumber); return IMG_NULL; } /* Reset list pointer */ psList = *ppsList; /* If we're trying to get a constant we need to figure out where to get it from */ if (eType == USEASM_REGTYPE_SECATTR) { IMG_BOOL bFitInSecondaries = IMG_FALSE; /* Alloc space for reg */ psRetReg = FFGENMalloc(psFFGenCode->psFFGenContext, sizeof(FFGenReg)); #ifdef FFGEN_UNIFLEX if(IF_FFGENCODE_UNIFLEX) { /* USC compiler deals with memory allocation, so just pretend that we always have enough space for secondary attributes */ goto UseSecondaries; } #endif /* Can we put this constant into the secondary attributes? */ if(bIndexableSecondary) { if((psFFGenCode->uHighSecAttribSize + uSize + EURASIA_USE_REGISTER_NUMBER_MAX) <= psFFGenCode->uMaxSecAttribSize) { psRetReg->eType = USEASM_REGTYPE_SECATTR; psRetReg->eWDFStatus = 0; psRetReg->uOffset = psFFGenCode->uHighSecAttribSize + EURASIA_USE_REGISTER_NUMBER_MAX; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of regs alloced */ psFFGenCode->uHighSecAttribSize += uSize; bFitInSecondaries = IMG_TRUE; /* add to Indexable Secondary list */ psFFGenCode->psIndexableSecondaryList = AddRegToList(psFFGenCode, psFFGenCode->psIndexableSecondaryList, psRetReg, IMG_FALSE, uLineNumber, pszFileName); } } else if (psFFGenCode->uSecAttribSize + uSize <= EURASIA_USE_REGISTER_NUMBER_MAX) { #ifdef FFGEN_UNIFLEX UseSecondaries: if(IF_FFGENCODE_UNIFLEX) { /* If we are using FFGen to make UniFlex instructions, then we always start on a vector 4 boundary, so that vector UniFlex instructions work. Otherwise, a vector could span across a boundary. */ if(psFFGenCode->uSecAttribSize % 4) psFFGenCode->uSecAttribSize += 4 - (psFFGenCode->uSecAttribSize % 4); } #endif psRetReg->eType = USEASM_REGTYPE_SECATTR; psRetReg->eWDFStatus = 0; psRetReg->uOffset = psFFGenCode->uSecAttribSize; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of regs alloced */ psFFGenCode->uSecAttribSize += uSize; bFitInSecondaries = IMG_TRUE; } /* Nope will have to go into the temporaries */ if(!bFitInSecondaries) { psRetReg->eType = USEASM_REGTYPE_TEMP; psRetReg->uOffset = psFFGenCode->uMemoryConstantsSize; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of regs alloced */ psFFGenCode->uMemoryConstantsSize += uSize; /* This constant needs loading */ if (!bAllocSpaceOnly) { bConstantLoadRequired = IMG_TRUE; } } } else if ((eType == USEASM_REGTYPE_OUTPUT) && (psFFGenCode->eCodeGenFlags & FFGENCGF_REDIRECT_OUTPUT_TO_INPUT)) { /* redirect output reg to temp - will get copied out at end */ psRetReg = GetTemp(psFFGenCode, uSize, uLineNumber, pszFileName); /* Not normally set up for temps */ psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of regs alloced */ *puCurrentAllocSize += uSize; } else { /* Alloc space for reg */ psRetReg = FFGENMalloc(psFFGenCode->psFFGenContext, sizeof(FFGenReg)); /* Setup the register */ psRetReg->eType = eType; psRetReg->uOffset = *puCurrentAllocSize; psRetReg->uSizeInDWords = uSize; psRetReg->eBindingRegDesc = eBindingRegDesc; psRetReg->eWDFStatus = 0; psRetReg->uIndex = USEREG_INDEX_NONE; /* Increase size of regs alloced */ *puCurrentAllocSize += uSize; } /* Add this register to the relevant list */ *ppsList = AddRegToList(psFFGenCode, psList, psRetReg, IMG_FALSE, uLineNumber, pszFileName); /* Do we need to perform a constant load? */ if (bConstantLoadRequired) { return LoadConstant(psFFGenCode, psRetReg, uSize, uLoadOffsetInDWords, psIndexReg, pszDesc, bFCLFillLoad, uLineNumber, pszFileName); } return psRetReg; } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ IMG_INTERNAL IMG_BOOL StoreRegfn(FFGenCode *psFFGenCode, FFGenRegDesc eBindingRegDesc, FFGENIndexReg *psIndexReg, IMG_UINT32 uOffsetInDWords, IMG_UINT32 uSizeInDWords, FFGenReg *psStoreSrc, IMG_BOOL bIssueWDFImmediately, IMG_CHAR *pszDesc, IMG_UINT32 uLineNumber, IMG_CHAR *pszFileName) { FFGenReg *psReg, *psRetReg = IMG_NULL; FFGenRegList **ppsList, *psList; if (!uSizeInDWords) { psFFGenCode->psFFGenContext->pfnPrint("StoreReg: Size was 0 (%s, %d)\n", pszFileName, uLineNumber); return IMG_FALSE; } /* Get constant list */ ppsList = &(psFFGenCode->psConstantsList); /* Reset list */ psList = *ppsList; /* Search through input list to see if this has already been allocated */ while (psList && !psRetReg) { psReg = psList->psReg; /* Get next entry */ psList = psList->psNext; /* Does binding info match */ if (psReg->eBindingRegDesc == eBindingRegDesc) { /* Check whether size is out of range. */ if(uOffsetInDWords + uSizeInDWords > psReg->uSizeInDWords) { psFFGenCode->psFFGenContext->pfnPrint("StoreReg: size + offset is greater than original alloc size(%s, %d)!\n", pszFileName, uLineNumber); return IMG_FALSE; } if(psReg->eType == USEASM_REGTYPE_TEMP) { LoadStoreConstant(psFFGenCode, IMG_FALSE, /* bLoad ? not, it is a store */ psReg, /* psConstReg */ uSizeInDWords, /* size to store */ uOffsetInDWords, /* Offset */ psIndexReg, /* Supplied index reg ? */ psStoreSrc, /* Store from */ pszDesc, IMG_FALSE, /* bFCLFillLoad? not related */ bIssueWDFImmediately, uLineNumber, pszFileName); return IMG_TRUE; } else if(psReg->eType == USEASM_REGTYPE_SECATTR) { psFFGenCode->psFFGenContext->pfnPrint("StoreReg: Can not store to secondary attribute"); return IMG_FALSE; } } } psFFGenCode->psFFGenContext->pfnPrint("StoreReg: Original register is not allocated (%s, %d)\n", pszFileName, uLineNumber); return IMG_FALSE; } /****************************************************************************** * Function Name: * * Inputs : * Outputs : - * Returns : * Globals Used : - * * Description : *****************************************************************************/ IMG_INTERNAL IMG_VOID DestroyRegList(FFGenContext *psFFGenContext, FFGenRegList *psList, IMG_BOOL bFreeReg) { while (psList) { FFGenRegList *psNext = psList->psNext; if (bFreeReg) { #if defined(OGLES1_MODULE) && defined(FFGEN_UNIFLEX) if(psList->psReg->pui32SrcOffset) { FFGENFree(psFFGenContext, psList->psReg->pui32SrcOffset); } if(psList->psReg->pui32DstOffset) { FFGENFree(psFFGenContext, psList->psReg->pui32DstOffset); } #endif /* defined(OGLES1_MODULE) && defined(FFGEN_UNIFLEX) */ /* free the register */ FFGENFree(psFFGenContext, psList->psReg); } /* Free the entry */ FFGENFree(psFFGenContext, psList); psList = psNext; } } /****************************************************************************** End of file (reg.c) ******************************************************************************/
27.171983
159
0.626053
[ "vector" ]
8d64b86b29193d7e1e6e9f62bfa9ef90c053e260
247
h
C
src/vm/api.h
PrinceDhaliwal/grok-exprimental
4db619a91e235c9d0da5bb5a11f7e643f999e022
[ "Apache-2.0" ]
5
2015-12-31T16:30:16.000Z
2019-07-13T15:50:15.000Z
src/vm/api.h
PrinceDhaliwal/grok-exprimental
4db619a91e235c9d0da5bb5a11f7e643f999e022
[ "Apache-2.0" ]
null
null
null
src/vm/api.h
PrinceDhaliwal/grok-exprimental
4db619a91e235c9d0da5bb5a11f7e643f999e022
[ "Apache-2.0" ]
null
null
null
#ifndef VM_API_H_ #define VM_API_H_ #include "object/jsbasicobject.h" #include "object/jsobject.h" #include "object/argument.h" namespace grok { namespace vm { using GrokFunction = Value (*) (std::shared_ptr<grok::obj::Argument>); } } #endif
14.529412
70
0.728745
[ "object" ]
8d65772059aaf3b6d7b2cf81e0aa5b3b670862e2
3,308
h
C
chrome/browser/media/midi_permission_context.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
chrome/browser/media/midi_permission_context.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/media/midi_permission_context.h
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright 2013 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 CHROME_BROWSER_MEDIA_MIDI_PERMISSION_CONTEXT_H_ #define CHROME_BROWSER_MEDIA_MIDI_PERMISSION_CONTEXT_H_ #include "base/containers/scoped_ptr_hash_map.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "components/keyed_service/core/keyed_service.h" namespace content { class WebContents; } class GURL; class MidiPermissionRequest; class PermissionQueueController; class PermissionRequestID; class Profile; // This class manages MIDI permissions flow. Used on the UI thread. class MidiPermissionContext : public KeyedService { public: explicit MidiPermissionContext(Profile* profile); virtual ~MidiPermissionContext(); // KeyedService methods: virtual void Shutdown() OVERRIDE; // Request to ask users permission about MIDI. void RequestMidiSysExPermission( content::WebContents* web_contents, int bridge_id, const GURL& requesting_frame, bool user_gesture, const base::Callback<void(bool)>& result_callback, base::Closure* cancel_callback); // Called when the permission decision is made. If a permissions prompt is // shown to the user it will be called when the user selects an option // from that prompt. void NotifyPermissionSet( const PermissionRequestID& id, const GURL& requesting_frame, const base::Callback<void(bool)>& callback, bool allowed); private: friend class MidiPermissionRequest; // Cancel a pending MIDI permission request. void CancelMidiSysExPermissionRequest(int render_process_id, int render_view_id, int bridge_id); // Decide whether the permission should be granted. // Calls PermissionDecided if permission can be decided non-interactively, // or NotifyPermissionSet if permission decided by presenting an infobar. void DecidePermission( content::WebContents* web_contents, const PermissionRequestID& id, const GURL& requesting_frame, const GURL& embedder, bool user_gesture, const base::Callback<void(bool)>& callback); // Called when permission is granted without interactively asking the user. void PermissionDecided( const PermissionRequestID& id, const GURL& requesting_frame, const GURL& embedder, const base::Callback<void(bool)>& callback, bool allowed); // Return an instance of the infobar queue controller, creating it if needed. PermissionQueueController* GetQueueController(); // Removes any pending InfoBar request. void CancelPendingInfobarRequest(const PermissionRequestID& id); // Notify the context that a particular request object is no longer needed. void RequestFinished(MidiPermissionRequest* request); Profile* const profile_; bool shutting_down_; scoped_ptr<PermissionQueueController> permission_queue_controller_; base::ScopedPtrHashMap<std::string, MidiPermissionRequest> pending_requests_; base::WeakPtrFactory<MidiPermissionContext> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MidiPermissionContext); }; #endif // CHROME_BROWSER_MEDIA_MIDI_PERMISSION_CONTEXT_H_
33.755102
79
0.751814
[ "object" ]
8d6e2bf6b12ce7da734881389aaaab62a52ab5c6
1,951
h
C
media/midi/usb_midi_device_android.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-16T13:10:29.000Z
2021-11-16T13:10:29.000Z
media/midi/usb_midi_device_android.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/midi/usb_midi_device_android.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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 MEDIA_MIDI_USB_MIDI_DEVICE_ANDROID_H_ #define MEDIA_MIDI_USB_MIDI_DEVICE_ANDROID_H_ #include <jni.h> #include <stdint.h> #include <memory> #include <string> #include <vector> #include "base/android/scoped_java_ref.h" #include "base/callback.h" #include "media/midi/usb_midi_device.h" #include "media/midi/usb_midi_export.h" namespace midi { class USB_MIDI_EXPORT UsbMidiDeviceAndroid : public UsbMidiDevice { public: static std::unique_ptr<Factory> CreateFactory(); UsbMidiDeviceAndroid() = delete; UsbMidiDeviceAndroid(const base::android::JavaRef<jobject>& raw_device, UsbMidiDeviceDelegate* delegate); UsbMidiDeviceAndroid(const UsbMidiDeviceAndroid&) = delete; UsbMidiDeviceAndroid& operator=(const UsbMidiDeviceAndroid&) = delete; ~UsbMidiDeviceAndroid() override; // UsbMidiDevice implementation. std::vector<uint8_t> GetDescriptors() override; std::string GetManufacturer() override; std::string GetProductName() override; std::string GetDeviceVersion() override; void Send(int endpoint_number, const std::vector<uint8_t>& data) override; // Called by the Java world. void OnData(JNIEnv* env, jint endpoint_number, const base::android::JavaParamRef<jbyteArray>& data); private: void GetDescriptorsInternal(); void InitDeviceInfo(); std::vector<uint8_t> GetStringDescriptor(int index); std::string GetString(int index, const std::string& backup); // The actual device object. base::android::ScopedJavaGlobalRef<jobject> raw_device_; UsbMidiDeviceDelegate* delegate_; std::vector<uint8_t> descriptors_; std::string manufacturer_; std::string product_; std::string device_version_; }; } // namespace midi #endif // MEDIA_MIDI_USB_MIDI_DEVICE_ANDROID_H_
29.560606
76
0.752435
[ "object", "vector" ]
8d74d5706514d15317142865d53ffcacd58ea449
1,699
c
C
ccder/src/ccder_decode_uint.c
rajohns08/corecrypto
0344fab1747c1e187f12233f353d73c331a77653
[ "AML" ]
null
null
null
ccder/src/ccder_decode_uint.c
rajohns08/corecrypto
0344fab1747c1e187f12233f353d73c331a77653
[ "AML" ]
null
null
null
ccder/src/ccder_decode_uint.c
rajohns08/corecrypto
0344fab1747c1e187f12233f353d73c331a77653
[ "AML" ]
null
null
null
/* Copyright (c) (2012,2015,2016,2019) Apple Inc. All rights reserved. * * corecrypto is licensed under Apple Inc.’s Internal Use License Agreement (which * is contained in the License.txt file distributed with corecrypto) and only to * people who accept that license. IMPORTANT: Any license rights granted to you by * Apple Inc. (if any) are limited to internal use within your organization only on * devices and computers you own or control, for the sole purpose of verifying the * security characteristics and correct functioning of the Apple Software. You may * not, directly or indirectly, redistribute the Apple Software or any portions thereof. */ #include <corecrypto/ccder.h> #include <corecrypto/ccder_priv.h> #include "ccder_internal.h" static const uint8_t *ccder_decode_uint_internal(cc_size n, cc_unit *r, const uint8_t *der, const uint8_t *der_end, bool strict) { size_t len; der = ccder_decode_tl_internal(CCDER_INTEGER, &len, der, der_end, strict); if (der && (der + len) <= der_end) { // Find most significant byte der = ccder_decode_uint_skip_leading_zeroes(&len, der); // Transform the byte array in cc_unit array if (!r || !der || ccn_read_uint(n, r, len, der) < 0) { goto errOut; } return der + len; } errOut: return NULL; } const uint8_t *ccder_decode_uint_strict(cc_size n, cc_unit *r, const uint8_t *der, const uint8_t *der_end) { return ccder_decode_uint_internal(n, r, der, der_end, true); } const uint8_t *ccder_decode_uint(cc_size n, cc_unit *r, const uint8_t *der, const uint8_t *der_end) { return ccder_decode_uint_internal(n, r, der, der_end, false); }
38.613636
128
0.711595
[ "transform" ]
8d79ecce9d80508f2702c149067030fbfb303787
9,666
h
C
include/Header.h
zjliucn/libHSL
3f1a203948118fc38a431f57337461da37d10ede
[ "BSD-2-Clause" ]
null
null
null
include/Header.h
zjliucn/libHSL
3f1a203948118fc38a431f57337461da37d10ede
[ "BSD-2-Clause" ]
null
null
null
include/Header.h
zjliucn/libHSL
3f1a203948118fc38a431f57337461da37d10ede
[ "BSD-2-Clause" ]
1
2021-12-11T13:29:21.000Z
2021-12-11T13:29:21.000Z
/****************************************************************************** * Copyright (c) 2021, Zhengjun Liu, Howard Butler * * 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 Martin Isenburg or Iowa Department * of Natural Resources 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. ****************************************************************************/ #pragma once #include <cstddef> #include <string> #include <vector> #include <iostream> #include <sstream> #include <cmath> #include <memory> #include "Singleton.h" #include "hslDefinitions.h" #include "Schema.h" #include "Bounds.h" namespace hsl { /// Definition of the header block that contains set of generic data and metadata /// describing the hyperspectral point cloud files. The header is stored /// at the beginning of every valid *.hsp file and its georeference file named *.prj. /// /// class LIBHSL_API Header { public: /// Default constructor. /// The default constructed header is configured similar to the ASPRS /// LAS 1.2 Specification, point data format set to 0. /// Other fields filled with 0. Header(); Header(PointFormat format); Header(const Schema &schema); /// Copy constructor. Header(Header const& other); /// Assignment operator. Header& operator=(Header const& rhs); /// Comparison operator. bool operator==(const Header& other) const; /// Get file signature. /// \return 5-characters long string - \b "HSPCD". std::string getFileSignature() const; /// Set file signature. /// The only value allowed as file signature is \b "HSPCD", /// defined as FileSignature constant. /// \exception std::invalid_argument - if invalid signature given. /// \param v - string contains file signature, at least 5-bytes long /// with "HSPCD" as first four bytes. void setFileSignature(std::string const& v); /// Get major component of version of HSP format. /// \return Always 1 is returned as the only valid value. uint8_t getVersionMajor() const; /// Set major component of version of HSP format. /// \exception std::out_of_range - invalid value given. /// \param v - value between eVersionMajorMin and eVersionMajorMax. void setVersionMajor(uint8_t v); /// Get minor component of version of HSP format. /// \return Valid values are 0, 1, 2, 3. uint8_t getVersionMinor() const; /// Set minor component of version of HSP format. /// \exception std::out_of_range - invalid value given. /// \param v - value between FV_VersionMinorMin and FV_VersionMinorMax. void setVersionMinor(uint8_t v); /// Get number of bytes from the beginning to the first point record. uint32_t getDataOffset() const; /// Set number of bytes from the beginning to the first point record. void setDataOffset(uint32_t v); /// Initialize point data format from predefined format. void setDataFormat(PointFormat v); /// The length in bytes of each point. All points in the file are /// considered to be fixed in size, and the PointFormat is used /// to determine the fixed portion of the dimensions in the point. Any /// other byte space in the point record beyond the liblas::Schema::GetBaseByteSize() /// can be used for other, optional, dimensions. uint32_t getDataRecordLength() const; /// Get total number of point records stored in the *.hsp file. uint64_t getPointRecordsCount() const; /// Set number of point records that will be stored in a new *.hsp file. void setPointRecordsCount(uint64_t v); /// Set number of returns that will be stored in a new *.hsp file. void setReturnCount(uint32_t v); /// Get the return count of the total point records uint32_t getReturnCount() const; /// Set values of total point records per return. /// \param index - subscript of array element being updated. /// \param v - new value to assign to array element identified by index. bool setPointRecordByReturn(std::size_t index, uint64_t v); uint64_t getPointRecordByReturn(std::size_t index) const; std::vector<uint64_t> getPointRecordsByReturnCount() const; /// Get scale factor for X coordinate. double getScaleX() const; /// Get scale factor for Y coordinate. double getScaleY() const; /// Get scale factor for Z coordinate. double getScaleZ() const; /// Set values of scale factor for X, Y and Z coordinates. void setScale(double x, double y, double z); /// Get X coordinate offset. double getOffsetX() const; /// Get Y coordinate offset. double getOffsetY() const; /// Get Z coordinate offset. double getOffsetZ() const; /// Set values of X, Y and Z coordinates offset. void setOffset(double x, double y, double z); /// Get minimum value of extent of X coordinate. double getMaxX() const; /// Get maximum value of extent of X coordinate. double getMinX() const; /// Get minimum value of extent of Y coordinate. double getMaxY() const; /// Get maximum value of extent of Y coordinate. double getMinY() const; /// Get minimum value of extent of Z coordinate. double getMaxZ() const; /// Get maximum value of extent of Z coordinate. double getMinZ() const; /// Set maximum values of extent of X, Y and Z coordinates. void setMax(double x, double y, double z); /// Set minimum values of extent of X, Y and Z coordinates. void setMin(double x, double y, double z); /// Returns the schema. const Schema & getSchema() const; Schema & getSchema(); /// Sets the schema void setSchema(const Schema& schema); /// Return the Bounds. This is a /// combination of the GetMax and GetMin /// (or getMinX, getMaxY, etc) data. const Bounds<double>& getExtent() const; /// Set the Bounds. This is a combination of the GetMax and GetMin /// (or getMinX, getMaxY, etc) data, and it is equivalent to setting /// all of these values. void setExtent(Bounds<double> const& extent); /// Returns true if the file is compressed, /// as determined by the high bit in the point type bool isCompressed() const; /// Sets whether or not the points are compressed. void setCompressed(bool b); bool hasWaveformData() const; bool addWaveformPacketDesc(const WaveformPacketDesc &descriptor); bool isInternalWaveformData() const; void setInternalWaveformData(bool b); bool isInternalBandData() const; void setInternalBandData(bool b); std::shared_ptr<FileHeader> getFileHeader() const { return _fileHeader; } void setFileHeader(std::shared_ptr<FileHeader> fileHeader) { _fileHeader = fileHeader; } std::shared_ptr<BlockDesc> getBlockDesc() const { return _blockDesc; } void setBlockDesc(std::shared_ptr<BlockDesc> blockDesc) { _blockDesc = blockDesc; } std::shared_ptr<WaveformDesc> getWaveformDesc() { return _waveformDesc; } void setWaveformDesc(std::shared_ptr<WaveformDesc> waveformDesc) { _waveformDesc = waveformDesc; } void updateHeader(); private: void init(); size_t calculateHeaderSize(); private: static const unsigned short _FileSignatureSize; static const std::string _FileSignature; std::shared_ptr<FileHeader> _fileHeader; std::vector<uint64_t> _pointRecordsByReturn; std::shared_ptr<BlockDesc> _blockDesc; std::shared_ptr<WaveformDesc> _waveformDesc; Schema _schema; bool _isCompressed; }; /// Singleton used for all empty points upon construction. If /// a reader creates the point, the HeaderPtr from the file that was /// read will be used, but all stand-alone points will have EmptyHeader /// as their base. class LIBHSL_API DefaultHeader : public Singleton<Header> { public: ~DefaultHeader() {} protected: DefaultHeader(); DefaultHeader( DefaultHeader const&); DefaultHeader& operator=( DefaultHeader const&); }; typedef std::shared_ptr<Header> HeaderPtr; typedef std::shared_ptr<const Header> ConstHeaderPtr; }
35.406593
99
0.683944
[ "vector" ]
8d7aa37bf373604183ffb014c1db40ebc5012c01
1,292
h
C
src/mainwindow.h
udit01/qGL
81aa4cdc7a271099c9ba8bee53e6aeba33c2901c
[ "MIT" ]
null
null
null
src/mainwindow.h
udit01/qGL
81aa4cdc7a271099c9ba8bee53e6aeba33c2901c
[ "MIT" ]
null
null
null
src/mainwindow.h
udit01/qGL
81aa4cdc7a271099c9ba8bee53e6aeba33c2901c
[ "MIT" ]
null
null
null
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QSlider> #include "model.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); Model *model; bool wireframe; ~MainWindow(); signals: void wireframeVal(bool b); void getModel(Model* m); void update(); protected: float tr_x ; float tr_y ; float tr_z ; float dalpha; float dbeta; float dgamma; void keyPressEvent(QKeyEvent *event); private slots: void on_pushButton_2_clicked(); void on_pushButton_clicked(); void on_actionNew_triggered(); void on_actionImport_triggered(); void on_tx_textEdited(const QString &arg1); void on_ty_textEdited(const QString &arg1); void on_tz_textEdited(const QString &arg1); void on_alphaSlider_valueChanged(int value); void on_betaSlider_valueChanged(int value); void on_gammaSlider_valueChanged(int value); void on_actionExport_triggered(); void on_actionTriangular_Pyramid_triggered(); void on_actionSquare_Pyramid_triggered(); void on_actionTriangular_Prism_triggered(); void on_actionCube_triggered(); private: Ui::MainWindow *ui; MainWindow *newWindow; }; #endif // MAINWINDOW_H
23.490909
49
0.732198
[ "model" ]
8d806287a5cbe9c1db65361cf1a99c8e42ca773b
8,382
h
C
dev/Gems/GraphCanvas/Code/Include/GraphCanvas/Widgets/GraphCanvasTreeModel.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2018-08-17T21:05:55.000Z
2021-04-17T10:48:26.000Z
dev/Gems/GraphCanvas/Code/Include/GraphCanvas/Widgets/GraphCanvasTreeModel.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
null
null
null
dev/Gems/GraphCanvas/Code/Include/GraphCanvas/Widgets/GraphCanvasTreeModel.h
horvay/lumberyardtutor
63b0681a7ed2a98d651b699984de92951721353e
[ "AML" ]
5
2017-12-05T16:36:00.000Z
2021-04-27T06:33:54.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <QAbstractItemModel> #include <qmimedata.h> #include <AzCore/EBus/EBus.h> #include <AzCore/Memory/SystemAllocator.h> #include <AzCore/std/smart_ptr/unique_ptr.h> #include <GraphCanvas/Widgets/GraphCanvasMimeContainer.h> #include <GraphCanvas/Widgets/GraphCanvasMimeEvent.h> #include <GraphCanvas/Widgets/GraphCanvasTreeItem.h> namespace GraphCanvas { class GraphCanvasTreeModelRequests : public AZ::EBusTraits { public: static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; using BusIdType = GraphCanvasTreeModel*; virtual void ClearSelection() = 0; }; using GraphCanvasTreeModelRequestBus = AZ::EBus<GraphCanvasTreeModelRequests>; //! Contains all the information required to build any Tree based widget that will support Drag/Drop with the GraphicsView. class GraphCanvasTreeModel : public QAbstractItemModel { public: AZ_CLASS_ALLOCATOR(GraphCanvasTreeModel, AZ::SystemAllocator, 0); static void Reflect(AZ::ReflectContext* reflectContext); GraphCanvasTreeModel(GraphCanvasTreeItem* treeRoot, QObject* parent = nullptr) : QAbstractItemModel(parent) , m_treeRoot(treeRoot) { } ~GraphCanvasTreeModel() = default; QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override { if (!hasIndex(row, column, parent)) { return QModelIndex(); } GraphCanvasTreeItem* parentItem; if (!parent.isValid()) { parentItem = m_treeRoot.get(); } else { parentItem = static_cast<GraphCanvasTreeItem*>(parent.internalPointer()); } GraphCanvasTreeItem* childItem = parentItem->ChildForRow(row); if (childItem) { QModelIndex modelIndex = createIndex(row, column, childItem); childItem->RegisterModel(const_cast<GraphCanvasTreeModel*>(this), modelIndex); return modelIndex; } else { return QModelIndex(); } } QModelIndex parent(const QModelIndex& index) const override { if (!index.isValid()) { return QModelIndex(); } GraphCanvasTreeItem* childItem = static_cast<GraphCanvasTreeItem*>(index.internalPointer()); GraphCanvasTreeItem* parentItem = childItem->GetParent(); if ((!parentItem) || (parentItem == m_treeRoot.get())) { return QModelIndex(); } QModelIndex modelIndex = createIndex(parentItem->FindRowUnderParent(), index.column(), parentItem); parentItem->RegisterModel(const_cast<GraphCanvasTreeModel*>(this), modelIndex); return modelIndex; } int columnCount(const QModelIndex& parent = QModelIndex()) const override { if (parent.isValid() && parent.internalPointer() != nullptr) { return static_cast<GraphCanvasTreeItem*>(parent.internalPointer())->GetColumnCount(); } else { return m_treeRoot->GetColumnCount(); } } int rowCount(const QModelIndex& parent = QModelIndex()) const override { GraphCanvasTreeItem* parentItem; if (parent.column() > 0) { return 0; } if (!parent.isValid()) { parentItem = m_treeRoot.get(); } else { parentItem = static_cast<GraphCanvasTreeItem*>(parent.internalPointer()); } return parentItem->GetNumChildren(); } QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { if (!index.isValid()) { return QVariant(); } GraphCanvasTreeItem* item = static_cast<GraphCanvasTreeItem*>(index.internalPointer()); return item->Data(index, role); } Qt::ItemFlags flags(const QModelIndex& index) const override { if (!index.isValid()) { return 0; } GraphCanvasTreeItem* item = static_cast<GraphCanvasTreeItem*>(index.internalPointer()); return item->Flags(index); } void setMimeType(const char* mimeType) { m_mimeType = mimeType; } QStringList mimeTypes() const override { QStringList list; list.append(m_mimeType); return list; } QMimeData* mimeData(const QModelIndexList& indexes) const { if (m_mimeType.isEmpty()) { return nullptr; } GraphCanvasMimeContainer container; for (const QModelIndex& index : indexes) { GraphCanvasTreeItem* item = static_cast<GraphCanvasTreeItem*>(index.internalPointer()); GraphCanvasMimeEvent* mimeEvent = item->CreateMimeEvent(); if (mimeEvent) { container.m_mimeEvents.push_back(mimeEvent); } } if (container.m_mimeEvents.empty()) { return nullptr; } AZStd::vector<char> encoded; if (!container.ToBuffer(encoded)) { return nullptr; } QMimeData* mimeDataPtr = new QMimeData(); QByteArray encodedData; encodedData.resize((int)encoded.size()); memcpy(encodedData.data(), encoded.data(), encoded.size()); mimeDataPtr->setData(m_mimeType, encodedData); return mimeDataPtr; } bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override { GraphCanvasTreeItem* parentItem = static_cast<GraphCanvasTreeItem*>(parent.internalPointer()); if (parentItem == nullptr) { return false; } if (row > parentItem->m_childItems.size()) { AZ_Error("Graph Canvas", false, "Trying to remove invalid row from GraphCanvasTreeModel."); return false; } else if (row + count > parentItem->m_childItems.size()) { AZ_Warning("Graph Canvas", false, "Trying to remove too many rows from GraphCanvasTreeModel."); count = (static_cast<int>(parentItem->m_childItems.size()) - row); } if (count == 0) { return true; } GraphCanvasTreeModelRequestBus::Event(this, &GraphCanvasTreeModelRequests::ClearSelection); beginRemoveRows(parent, row, row + (count - 1)); for (int i=0; i < count; ++i) { GraphCanvasTreeItem* childItem = parentItem->m_childItems[row + i]; childItem->RemoveParent(parentItem); if (parentItem->m_deleteRemoveChildren) { delete childItem; } } parentItem->m_childItems.erase(parentItem->m_childItems.begin() + row, parentItem->m_childItems.begin() + row + count); endRemoveRows(); return true; } public: QString m_mimeType; AZStd::unique_ptr<GraphCanvasTreeItem> m_treeRoot; }; }
31.511278
131
0.559652
[ "vector" ]
8d8b132a0d677c045f5c1441a3c867293c96e599
2,572
h
C
sources/mach_plugin/ConfigDialog.h
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
6
2019-05-22T03:18:38.000Z
2022-02-07T20:54:38.000Z
sources/mach_plugin/ConfigDialog.h
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
1
2019-11-10T05:57:09.000Z
2020-07-01T05:50:49.000Z
sources/mach_plugin/ConfigDialog.h
mariusl/step2mach
3ac7ff6c3b29a25f4520e4325e7922f2d34c547a
[ "MIT" ]
9
2019-05-20T06:03:55.000Z
2022-02-01T10:16:41.000Z
#pragma once using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; namespace mach_plugin { /// <summary> /// Summary for ConfigDialog /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class ConfigDialog : public System::Windows::Forms::Form { public: ConfigDialog(void) { InitializeComponent(); // //TODO: Add the constructor code here // } protected: /// <summary> /// Clean up any resources being used. /// </summary> ~ConfigDialog() { if (components) { delete components; } } private: System::Windows::Forms::Label^ label1; protected: private: /// <summary> /// Required designer variable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->label1 = (gcnew System::Windows::Forms::Label()); this->SuspendLayout(); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(19, 36); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(205, 26); this->label1->TabIndex = 0; this->label1->Text = L"Configuration Screens Are Now Accessed\r\nThrough The \'PlugIn Control\' Menu"; this->label1->TextAlign = System::Drawing::ContentAlignment::MiddleCenter; // // ConfigDialog // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(349, 165); this->Controls->Add(this->label1); this->Name = L"ConfigDialog"; this->Text = L"ConfigDialog"; this->Load += gcnew System::EventHandler(this, &ConfigDialog::ConfigDialog_Load); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void ConfigDialog_Load(System::Object^ sender, System::EventArgs^ e) { } }; }
28.263736
105
0.674572
[ "object" ]
e453a8b998505ce6c33c51d0fce018282577c982
6,452
c
C
legacy/lib/c/src/bandpass_nifti/FFTW/fftw-3.1.2/tests/hook.c
ThomasYeoLab/Standalone_He2022_MM
6895f7b2830a6a521bc311e70f775a82b11e46e7
[ "MIT" ]
null
null
null
legacy/lib/c/src/bandpass_nifti/FFTW/fftw-3.1.2/tests/hook.c
ThomasYeoLab/Standalone_He2022_MM
6895f7b2830a6a521bc311e70f775a82b11e46e7
[ "MIT" ]
null
null
null
legacy/lib/c/src/bandpass_nifti/FFTW/fftw-3.1.2/tests/hook.c
ThomasYeoLab/Standalone_He2022_MM
6895f7b2830a6a521bc311e70f775a82b11e46e7
[ "MIT" ]
1
2022-03-12T08:21:59.000Z
2022-03-12T08:21:59.000Z
/* fftw hook to be used in the benchmark program. We keep it in a separate file because 1) bench.c is supposed to test the API---we do not want to #include "ifftw.h" and accidentally use internal symbols/macros. 2) this code is a royal mess. The messiness is due to A) confusion between internal fftw tensors and bench_tensor's (which we want to keep separate because the benchmark program tests other routines too) B) despite A), our desire to recycle the libbench verifier. */ #include <stdio.h> #include "bench-user.h" #define CALLING_FFTW /* hack for Windows DLL nonsense */ #include "api.h" #include "dft.h" #include "rdft.h" extern int paranoid; /* in bench.c */ extern X(plan) the_plan; /* in bench.c */ /* transform an fftw tensor into a bench_tensor. */ static bench_tensor *fftw_tensor_to_bench_tensor(tensor *t) { bench_tensor *bt = mktensor(t->rnk); if (FINITE_RNK(t->rnk)) { int i; for (i = 0; i < t->rnk; ++i) { /* FIXME: 64-bit unclean because of INT -> int conversion */ bt->dims[i].n = t->dims[i].n; bt->dims[i].is = t->dims[i].is; bt->dims[i].os = t->dims[i].os; BENCH_ASSERT(bt->dims[i].n == t->dims[i].n); BENCH_ASSERT(bt->dims[i].is == t->dims[i].is); BENCH_ASSERT(bt->dims[i].os == t->dims[i].os); } } return bt; } /* transform an fftw problem into a bench_problem. */ static bench_problem *fftw_problem_to_bench_problem(planner *plnr, const problem *p_) { bench_problem *bp = 0; switch (p_->adt->problem_kind) { case PROBLEM_DFT: { const problem_dft *p = (const problem_dft *) p_; if (!p->ri || !p->ii) abort(); bp = (bench_problem *) bench_malloc(sizeof(bench_problem)); bp->kind = PROBLEM_COMPLEX; bp->sign = FFT_SIGN; bp->split = 1; /* tensor strides are in R's, not C's */ bp->in = UNTAINT(p->ri); bp->out = UNTAINT(p->ro); bp->ini = UNTAINT(p->ii); bp->outi = UNTAINT(p->io); bp->inphys = bp->outphys = 0; bp->iphyssz = bp->ophyssz = 0; bp->in_place = p->ri == p->ro; bp->sz = fftw_tensor_to_bench_tensor(p->sz); bp->vecsz = fftw_tensor_to_bench_tensor(p->vecsz); bp->k = 0; break; } case PROBLEM_RDFT: { const problem_rdft *p = (const problem_rdft *) p_; int i; if (!p->I || !p->O) abort(); for (i = 0; i < p->sz->rnk; ++i) switch (p->kind[i]) { case R2HC01: case R2HC10: case R2HC11: case HC2R01: case HC2R10: case HC2R11: return bp; } bp = (bench_problem *) bench_malloc(sizeof(bench_problem)); bp->kind = PROBLEM_R2R; bp->sign = FFT_SIGN; bp->split = 0; bp->in = UNTAINT(p->I); bp->out = UNTAINT(p->O); bp->ini = bp->outi = 0; bp->inphys = bp->outphys = 0; bp->iphyssz = bp->ophyssz = 0; bp->in_place = p->I == p->O; bp->sz = fftw_tensor_to_bench_tensor(p->sz); bp->vecsz = fftw_tensor_to_bench_tensor(p->vecsz); bp->k = (r2r_kind_t *) bench_malloc(sizeof(r2r_kind_t) * p->sz->rnk); for (i = 0; i < p->sz->rnk; ++i) switch (p->kind[i]) { case R2HC: bp->k[i] = R2R_R2HC; break; case HC2R: bp->k[i] = R2R_HC2R; break; case DHT: bp->k[i] = R2R_DHT; break; case REDFT00: bp->k[i] = R2R_REDFT00; break; case REDFT01: bp->k[i] = R2R_REDFT01; break; case REDFT10: bp->k[i] = R2R_REDFT10; break; case REDFT11: bp->k[i] = R2R_REDFT11; break; case RODFT00: bp->k[i] = R2R_RODFT00; break; case RODFT01: bp->k[i] = R2R_RODFT01; break; case RODFT10: bp->k[i] = R2R_RODFT10; break; case RODFT11: bp->k[i] = R2R_RODFT11; break; default: CK(0); } break; } case PROBLEM_RDFT2: { const problem_rdft2 *p = (const problem_rdft2 *) p_; if (!p->r || !p->rio || !p->iio) abort(); bp = (bench_problem *) bench_malloc(sizeof(bench_problem)); bp->kind = PROBLEM_REAL; bp->sign = p->kind == R2HC ? FFT_SIGN : -FFT_SIGN; bp->split = 1; /* tensor strides are in R's, not C's */ if (p->kind == R2HC) { bp->sign = FFT_SIGN; bp->in = UNTAINT(p->r); bp->out = UNTAINT(p->rio); bp->ini = 0; bp->outi = UNTAINT(p->iio); } else { bp->sign = -FFT_SIGN; bp->out = UNTAINT(p->r); bp->in = UNTAINT(p->rio); bp->outi = 0; bp->ini = UNTAINT(p->iio); } bp->inphys = bp->outphys = 0; bp->iphyssz = bp->ophyssz = 0; bp->in_place = p->r == p->rio; bp->sz = fftw_tensor_to_bench_tensor(p->sz); bp->vecsz = fftw_tensor_to_bench_tensor(p->vecsz); bp->k = 0; break; } default: abort(); } bp->userinfo = 0; bp->pstring = 0; bp->destroy_input = !NO_DESTROY_INPUTP(plnr); return bp; } static void hook(planner *plnr, plan *pln, const problem *p_, int optimalp) { int rounds = 5; double tol = SINGLE_PRECISION ? 1.0e-3 : 1.0e-10; UNUSED(optimalp); if (verbose > 5) { printer *pr = X(mkprinter_file)(stdout); pr->print(pr, "%P:%(%p%)\n", p_, pln); X(printer_destroy)(pr); printf("cost %g \n\n", pln->pcost); } if (paranoid) { bench_problem *bp; bp = fftw_problem_to_bench_problem(plnr, p_); if (bp) { X(plan) the_plan_save = the_plan; the_plan = (apiplan *) MALLOC(sizeof(apiplan), PLANS); the_plan->pln = pln; the_plan->prb = (problem *) p_; X(plan_awake)(pln, AWAKE_SQRTN_TABLE); verify_problem(bp, rounds, tol); X(plan_awake)(pln, SLEEPY); X(ifree)(the_plan); the_plan = the_plan_save; problem_destroy(bp); } } } static void paranoid_checks(void) { /* FIXME: assumes char = 8 bits, which is false on at least one DSP I know of. */ #if 0 /* if flags_t is not 64 bits i want to know it. */ CK(sizeof(flags_t) == 8); CK(sizeof(md5uint) >= 4); #endif CK(sizeof(uintptr_t) >= sizeof(R *)); CK(sizeof(INT) >= sizeof(R *)); } void install_hook(void) { planner *plnr = X(the_planner)(); plnr->hook = hook; paranoid_checks(); } void uninstall_hook(void) { planner *plnr = X(the_planner)(); plnr->hook = 0; }
26.995816
76
0.556727
[ "transform" ]
e4551ea43ee966e6e12c70ec046b6059ebb38b45
1,613
c
C
item.c
pvc988/TableGen
d53ccce1573232e91380ba7fda634d1d62e9133a
[ "MIT" ]
1
2021-02-21T23:33:16.000Z
2021-02-21T23:33:16.000Z
item.c
pvc988/TableGen
d53ccce1573232e91380ba7fda634d1d62e9133a
[ "MIT" ]
null
null
null
item.c
pvc988/TableGen
d53ccce1573232e91380ba7fda634d1d62e9133a
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "item.h" #include "vector.h" typedef struct Symbol Symbol; static bool lookaheadsEquivalent(Item *a, Item *b) { if(a->Lookaheads->ItemCount != b->Lookaheads->ItemCount) return false; for(size_t i = 0; i < a->Lookaheads->ItemCount; ++i) { size_t eqCount = 0; Symbol *u = (Symbol *)a->Lookaheads->Items[i]; for(size_t i = 0; i < b->Lookaheads->ItemCount; ++i) { Symbol *v = (Symbol *)b->Lookaheads->Items[i]; if(u == v) { if(eqCount) return false; ++eqCount; } } if(eqCount != 1) return false; } return true; } Item *ItemCreate(bool core, Production *prod, size_t pos) { Item *item = (Item *)malloc(sizeof(Item)); item->Core = core; item->Production = prod; item->Position = pos; item->Lookaheads = VectorCreate(); return item; } Item *ItemCreateLA(bool core, Production *prod, size_t pos, Vector *lookaheads) { Item *item = (Item *)malloc(sizeof(Item)); item->Core = core; item->Production = prod; item->Position = pos; item->Lookaheads = lookaheads; return item; } void ItemDelete(Item *item) { if(item->Lookaheads) VectorDelete(item->Lookaheads); free(item); } bool ItemSimilar(Item *a, Item *b) { if(a == b) return true; if(a->Production != b->Production) return false; if(a->Position != b->Position) return false; return true; } bool ItemEquivalent(Item *a, Item *b) { return ItemSimilar(a, b) && lookaheadsEquivalent(a, b); }
22.71831
79
0.582765
[ "vector" ]
e455fe5423d49ccbedb0cb2ec8bad9e9a92d692a
3,756
h
C
Oem/DWFTK/develop/global/src/dwf/XAML/XamlImage.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/DWFTK/develop/global/src/dwf/XAML/XamlImage.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/DWFTK/develop/global/src/dwf/XAML/XamlImage.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (c) 2006 by Autodesk, Inc. // // By using this code, you are agreeing to the terms and conditions of // the License Agreement included in the documentation for this code. // // AUTODESK MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AS TO THE CORRECTNESS // OF THIS CODE OR ANY DERIVATIVE WORKS WHICH INCORPORATE IT. AUTODESK // PROVIDES THE CODE ON AN "AS-IS" BASIS AND EXPLICITLY DISCLAIMS ANY // LIABILITY, INCLUDING CONSEQUENTIAL AND INCIDENTAL DAMAGES FOR ERRORS, // OMISSIONS, AND OTHER PROBLEMS IN THE CODE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer Software // Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) (Rights in Technical // Data and Computer Software), as applicable. // #if !defined XAML_IMAGE_HEADER #define XAML_IMAGE_HEADER /// ///\file XAML/XamlImage.h /// #include "XAML/XamlCore.h" #include "whiptk/image.h" #include "XAML/XamlXML.h" /** \addtogroup groupDrawable * @{ */ /// A drawable describing an image (bitonal, color mapped, RGB, RGBA, JPEG.) /** <b> An example of creating all of the different image types is provided in the sample app * \em W2DTest accompanying the WHIP! Toolkit source distribution. It is too lengthy to be * included here in this API doc. </b> */ class XAMLTK_API WT_XAML_Image : public WT_Image { friend class WT_XAML_Class_Factory; protected: // Constructors, Destructors /// Constructs a WT_XAML_Image object. WT_XAML_Image () : WT_Image() { } /// Constructs a WT_XAML_Image object of the given type (one of \ref WT_Image_Format "enum WT_Image_Format".) WT_XAML_Image (int image_type) : WT_Image(image_type) { } /// Constructs a WT_XAML_Image object with the given data. WT_XAML_Image( WT_Unsigned_Integer16 rows, /**< Height of the image in pixels. */ WT_Unsigned_Integer16 columns, /**< Width of the image in pixels. */ WT_Image_Format format, /**< The image format (one of \ref WT_Image_Format "enum WT_Image_Format".)*/ WT_Integer32 identifier, /**< The unique numeric identifier of the image in the graphics collection. */ WT_Color_Map const * color_map, /**< The color map the image should use (if any.) */ WT_Integer32 data_size, /**< The size (in bytes) of the raw image data contained in the \a data argument. */ WT_Byte * data, /**< The raw pixel data. */ WT_Logical_Point const & min_corner, /**< The lower-left corner of the image. */ WT_Logical_Point const & max_corner, /**< The upper-right corner of the image. */ WT_Boolean copy, /**< Whether the pixel data should be copied or if it should be used directly from the buffer. */ WT_Integer32 dpi = -1 /**< Scanned resolution for the image. */ ) throw(WT_Result) : WT_Image(rows,columns,format,identifier,color_map,data_size,data,min_corner,max_corner,copy,dpi) { } WT_XAML_Image & operator= (WT_XAML_Image const &) { WD_Complain ("cannot assign WT_XAML_Image"); return *this; } // prohibited /// Destroys a WT_XAML_Image object. virtual ~WT_XAML_Image() { } public: //@{ \name WT_Object virtual methods WT_Result serialize(WT_File & /*file*/) const; /// partial materialization of shell from W2X WT_Result parseAttributeList(XamlXML::tAttributeMap& rMap, WT_XAML_File& rFile); }; //@} #endif //XAML_IMAGE_HEADER
41.274725
144
0.644569
[ "object" ]
e45ff702cd5d660e7a3eea5819b09543a6ef270b
1,541
h
C
tasmota/Tasmota-8.1.0/lib/IRremoteESP8266-2.7.1/src/ir_NEC.h
zorcec/SARAH
c7936ce9467fb11594b6ae4a937d6766060bec05
[ "MIT" ]
12
2019-08-22T08:48:01.000Z
2021-03-22T10:43:01.000Z
mixly_arduino/arduino/portable/sketchbook/libraries/IRremoteESP8266/src/ir_NEC.h
Chaiya2513/Mixly_Arduino
2902871112902edbe13d15f43d724fb176507e6e
[ "Apache-2.0" ]
1
2019-08-22T11:06:09.000Z
2019-08-22T11:06:09.000Z
mixly_arduino/arduino/portable/sketchbook/libraries/IRremoteESP8266/src/ir_NEC.h
Chaiya2513/Mixly_Arduino
2902871112902edbe13d15f43d724fb176507e6e
[ "Apache-2.0" ]
2
2019-08-22T09:12:55.000Z
2020-12-15T00:43:00.000Z
// Copyright 2009 Ken Shirriff // Copyright 2017, 2018 David Conran // NEC originally added from https://github.com/shirriff/Arduino-IRremote/ #ifndef IR_NEC_H_ #define IR_NEC_H_ #include <stdint.h> #include "IRremoteESP8266.h" // Supports: // Brand: Yamaha, Model: RAV561 remote // Brand: Yamaha, Model: RXV585B A/V Receiver // Constants // Ref: // http://www.sbprojects.com/knowledge/ir/nec.php const uint16_t kNecTick = 560; const uint16_t kNecHdrMarkTicks = 16; const uint16_t kNecHdrMark = kNecHdrMarkTicks * kNecTick; const uint16_t kNecHdrSpaceTicks = 8; const uint16_t kNecHdrSpace = kNecHdrSpaceTicks * kNecTick; const uint16_t kNecBitMarkTicks = 1; const uint16_t kNecBitMark = kNecBitMarkTicks * kNecTick; const uint16_t kNecOneSpaceTicks = 3; const uint16_t kNecOneSpace = kNecOneSpaceTicks * kNecTick; const uint16_t kNecZeroSpaceTicks = 1; const uint16_t kNecZeroSpace = kNecZeroSpaceTicks * kNecTick; const uint16_t kNecRptSpaceTicks = 4; const uint16_t kNecRptSpace = kNecRptSpaceTicks * kNecTick; const uint16_t kNecRptLength = 4; const uint16_t kNecMinCommandLengthTicks = 193; const uint32_t kNecMinCommandLength = kNecMinCommandLengthTicks * kNecTick; const uint32_t kNecMinGap = kNecMinCommandLength - (kNecHdrMark + kNecHdrSpace + kNECBits * (kNecBitMark + kNecOneSpace) + kNecBitMark); const uint16_t kNecMinGapTicks = kNecMinCommandLengthTicks - (kNecHdrMarkTicks + kNecHdrSpaceTicks + kNECBits * (kNecBitMarkTicks + kNecOneSpaceTicks) + kNecBitMarkTicks); #endif // IR_NEC_H_
34.244444
75
0.780662
[ "model" ]
e4604815e3e72141111296ef030979c8dd333f73
3,009
h
C
include/Material/Source/Polymerization/Factory.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/Material/Source/Polymerization/Factory.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/Material/Source/Polymerization/Factory.h
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// Factory.h: Factory for the Source::Polymerization class. // Copyright (c) 2017-2018 Extreme Computation Technology and Solutions, LLC // All rights reserved // see file License.txt for license details //////////////////////////////////////////////////////////////////////////// #if !defined(MATERIAL_SOURCE_POLYMERIZATION_FACTORY_H__INCLUDED_) #define MATERIAL_SOURCE_POLYMERIZATION_FACTORY_H__INCLUDED_ #pragma once #include <vector> #include "./Polymerization.h" #include "Material/Factory.h" namespace Material { namespace Source { namespace Polymerization { ////////////////////////////////////////////////////////////////////// // Class Factory ////////////////////////////////////////////////////////////////////// class Factory : public Material::Factory { public: typedef Material::Source::Polymerization::Data data_type; Factory() : LS(0), W(0), DW(0), DDW(0), J(0), DJ(0) {} virtual ~Factory() { if (LS != 0) delete LS; if (W != 0) delete W; } Factory(double T0_, Clock *Chronos_, Material::Source::Polymerization::Data *Dat_) : T0(T0_), Chronos(Chronos_), LS(0), W(0), DW(0), DDW(0), J(0), DJ(0), Dat(Dat_) {} Material::LocalState * GetLS() { if (LS == 0) LS = new Material::Source::Polymerization::LocalState(T0, Chronos, Dat); return LS; } Material::Energy<0> * GetW() { if (LS == 0) LS = new Material::Source::Polymerization::LocalState(T0, Chronos, Dat); if (W == 0) W = new Material::Source::Polymerization::Energy<0>(LS); return W; } Material::Energy<1> * GetDW() { return NULL; } Material::Energy<2> * GetDDW() { return NULL; } Material::Jet<0> * GetJ() { return NULL; } Material::Jet<1> * GetDJ() { return NULL; } private: double T0; Clock *Chronos; Material::Source::Polymerization::Data *Dat; Material::Source::Polymerization::LocalState *LS; Material::Source::Polymerization::Energy<0> *W; Material::Source::Polymerization::Energy<1> *DW; Material::Source::Polymerization::Energy<2> *DDW; Material::Source::Polymerization::Jet<0> *J; Material::Source::Polymerization::Jet<1> *DJ; private: Factory(const Factory &); Factory & operator = (const Factory &); }; ////////////////////////////////////////////////////////////////////// // Class Builder ////////////////////////////////////////////////////////////////////// class Builder : public Material::Builder { public: typedef Material::Source::Polymerization::Data data_type; typedef Material::Source::Polymerization::Factory fact_type; Builder() {} virtual ~Builder() {} Builder(double T0_, Clock *Chronos_, data_type *Dat_) : Dat(Dat_), Chronos(Chronos_), T0(T0_) {} Material::Factory * Build() const { return new fact_type(T0, Chronos, Dat); } private: double T0; Clock *Chronos; data_type *Dat; }; } } } #endif // !defined(MATERIAL_SOURCE_POLYMERIZATION_FACTORY_H__INCLUDED_
23.692913
94
0.576271
[ "vector" ]
e46083ddc81a35d633f79121e4e81ec52520057d
928
h
C
examples/Sandbox/src/Portal.h
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
examples/Sandbox/src/Portal.h
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
1
2018-06-02T20:11:47.000Z
2018-11-19T11:06:21.000Z
examples/Sandbox/src/Portal.h
Thraix/Greet-Engine-Port
9474a4f4b88a582289fc68e7fc3e62ba2c6d0ec8
[ "Apache-2.0" ]
null
null
null
#pragma once #include <graphics/models/EntityModel.h> #include <graphics/models/MeshFactory.h> #include <graphics/textures/TextureManager.h> #include <logging/Log.h> class Portal : public Greet::EntityModel { private: Greet::Ref<Greet::Mesh> mesh; float delta = 0.0f; public: Portal(const Greet::Vec3f& position) : Greet::EntityModel{nullptr, Greet::NewRef<Greet::Material>(Greet::Shader::FromFile("res/shaders/portal.glsl"), Greet::TextureManager::LoadTexture2D("res/textures/portal.meta")), position, {10,10,10}, {0,0,0}} { using namespace Greet; SetMesh(mesh = NewRef<Mesh>(MeshFactory::Plane({0, 0, 0}, {2, 2}))); } virtual ~Portal() {} void Update(float timeElapsed) override { delta += timeElapsed; } void PreRender() const override { EntityModel::PreRender(); GetMaterial()->GetShader()->SetUniform1f("time", delta); } };
25.081081
216
0.655172
[ "mesh" ]
e4695849185c579c0ea931ee9fca26c43b9720a4
4,973
h
C
ccnxlibs/libccnx-common/ccnx/common/codec/schema_v1/testdata/v1_content_nameA_crc32c.h
cherouvim/cicn-nrs
440d6a7f56e7240f179205ed5ce1fe8000d03b83
[ "Apache-2.0" ]
10
2018-11-04T06:37:14.000Z
2022-02-18T00:26:34.000Z
ccnxlibs/libccnx-common/ccnx/common/codec/schema_v1/testdata/v1_content_nameA_crc32c.h
cherouvim/cicn-nrs
440d6a7f56e7240f179205ed5ce1fe8000d03b83
[ "Apache-2.0" ]
null
null
null
ccnxlibs/libccnx-common/ccnx/common/codec/schema_v1/testdata/v1_content_nameA_crc32c.h
cherouvim/cicn-nrs
440d6a7f56e7240f179205ed5ce1fe8000d03b83
[ "Apache-2.0" ]
3
2019-01-17T19:47:55.000Z
2022-02-18T00:28:18.000Z
/* * Copyright (c) 2017 Cisco and/or its affiliates. * 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. */ /** * @file interest_nameA_crc32c.h * @brief Interest with CRC validation * * Ground truth set derived from CRC RevEng http://reveng.sourceforge.net * e.g. reveng -c -m CRC-32C 313233343536373839 gives the canonical check value 0xe306928e * * You can also calcaulate CRC32C online at http://www.zorc.breitbandkatze.de/crc.html using * CRC polynomial 0x1EDC6F41, init 0xFFFFFFFF, final 0xFFFFFFFF, reverse data bytes (check), * and reverse CRC result before final XOR (check). * * you can get the packet dump from the "write_packets" command. here's the detailed steps. * The -c size of 4 in steps 4 and 7 are chosen to make it easy to delete the right number of lines. * there's nothing magic about the "4". * * 1) execute ./write_packets * 2) xxd -r -c 8 v1_content_nameA_crc32c.txt > y * 3) vim -b y * 4) :%!xxd -p -c 4 * 5) Delete the frist 44 bytes (11 lines). The first line should now be: * 00020015 * 6) Delete the last 8 bytes * The last line two lines should be: * 04000200 * 00 * What's left is the part to be signed. * 7) :%!xxd -r -p -c 4 * 8) :wq * 9) dump the file to one long URL-escaped hex string with * xxd -p -c 256 y | sed 's/[0-9a-f]\{2\}/%&/g' * 10) Copy the hex string to the website and use the settings specified above (don't use 0x in front * of any hex strings). Click "compute!" * 11) The answer should be 2C3CC0Af * 12) Put the byte array from (11) in the Validation Payload. * */ #ifndef v1_content_nameA_crc32c_h #define v1_content_nameA_crc32c_h #include <ccnx/common/codec/testdata/testdata_common.h> #include <ccnx/common/codec/schema_v1/testdata/v1_ContentObjectSchema.h> /** * A well formed interest with only a name */ __attribute__((unused)) static uint8_t v1_content_nameA_crc32c[] = { 0x01, 0x01, 0x00, 85, // ver = 1, type = content object, length = 85 0x00, 0x00, 0x00, 44, // HopLimit = 31, reserved = 0, header length = 44 // ------------------------ 0x00, 0x04, 0x00, 20, // ContentObject Fragment, length = 20 0x12, 0x23, 0x34, 0x45, 0x56, 0x67, 0x78, 0x89, // fragid 0x1223344556677889 0x05, 0xDC, 0x01, 0x00, // MTU 1500, fragcnt 1, fragnum 0 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, // interest fragment 0x0102030405060708 // ------------------------ 0x00, 0x02, 0x00, 8, // Recommended Cache Time 0x00, 0x00, 0x00, 0x00, 0x00, 0x6D, 0xDD, 0x00, // 2 hours (0x6DDD00 milli seconds) // ------------------------ 0x00, 0x02, 0x00, 21, // type = content object, length = 21 // ------------------------ 0x00, 0x00, 0x00, 0x11, // type = name, length = 17 0x00, 0x03, 0x00, 0x05, // type = binary, length = 5 'h', 'e', 'l', 'l', // "hello" 'o', 0xF0, 0x00, 0x00, 0x04, // type = app, length = 4 'o', 'u', 'c', 'h', // "ouch" // ------------------------ 0x00, 0x03, 0x00, 4, // validation alg, length = 4 0x00, 0x02, 0x00, 0x00, // CRC32C // ------------------------ 0x00, 0x04, 0x00, 4, // validation payload 0x2C, 0x3C, 0xC0, 0xAF // 2C3CC0AF }; __attribute__((unused)) static TruthTableEntry TRUTHTABLENAME(v1_content_nameA_crc32c)[] = { { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_E2EFRAG, .bodyManifest = false, .extent = { 12, 20 } }, { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_RecommendedCacheTime, .bodyManifest = false, .extent = { 36, 8 } }, { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_CONTENTOBJECT, .bodyManifest = true, .extent = { 48, 21 } }, { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_NAME, .bodyManifest = true, .extent = { 52, 17 } }, { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_ValidationAlg, .bodyManifest = true, .extent = { 73, 4 } }, { .wellKnownType = true, .indexOrKey = V1_MANIFEST_OBJ_SIGBITS, .bodyManifest = true, .extent = { 81, 4 } }, { .wellKnownType = false, .indexOrKey = T_INVALID, .extent = { 0, 0 } }, }; #define v1_content_nameA_crc32c_truthTable TABLEENTRY(v1_content_nameA_crc32c, TLV_ERR_NO_ERROR) #define v1_content_nameA_crc32c_URI "lci:/3=hello/0xf000=ouch" #endif
43.243478
128
0.623969
[ "object" ]
e46ed6eecf2dc47a93742bf8f00951a04bbb6048
1,379
h
C
include/FrequencyQueue.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
1
2021-09-08T02:05:11.000Z
2021-09-08T02:05:11.000Z
include/FrequencyQueue.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
null
null
null
include/FrequencyQueue.h
coderwinnie/startalk_pc
30675f52204d798f4fef210a40ef9c5f1ac34ea9
[ "MIT" ]
null
null
null
// // Created by cc on 2020/1/9. // #ifndef QTALK_V2_FREQUENCYQUEUE_H #define QTALK_V2_FREQUENCYQUEUE_H #include <list> #include <mutex> #include <vector> template <class T> class FrequencyQueue { public: FrequencyQueue(unsigned int maxSize) { _maxListSize = maxSize; } ~FrequencyQueue() { for(const auto* pItem : _list) delete pItem; _list.clear(); } public: void insert(T t) { std::unique_lock<std::mutex> lock(_mutex); auto it = std::find(_list.begin(), _list.end(), t); if(it != _list.end()) _list.erase(it); _list.push_back(t); while (_list.size() > _maxListSize) { auto* old_item = _list.begin(); _list.erase(old_item); } } bool contains(T t) { std::unique_lock<std::mutex> lock(_mutex); return std::find(_list.begin(), _list.end(), t) != _list.end(); } std::vector<T> get(unsigned int count) { std::vector<T> res; auto it = _list.end(); int index = 0; while (it > _list.begin() && index++ < count ) { it--; res.push_back(*it); } return res; } private: std::list<T> _list; // unsigned int _maxListSize{}; std::mutex _mutex; }; #endif //QTALK_V2_FREQUENCYQUEUE_H
19.7
71
0.537346
[ "vector" ]
e477a49a7fae369ecdfdc0dfc7dcfd1b603f4e4a
11,845
h
C
src/infrastructure/repos.h
adipopbv/bookshopper-uni
58004036705b8b2c95d831a9e7c03f68593dde72
[ "MIT" ]
16
2020-10-02T15:04:11.000Z
2021-10-18T14:21:57.000Z
bookshopper-cpp/infrastructure/repos.h
UG-SEP/Friends_Hack
b1719389665a4a7d63e6736dca76904180f2f686
[ "MIT" ]
26
2020-10-02T11:57:42.000Z
2021-10-06T10:15:28.000Z
src/infrastructure/repos.h
adipopbv/bookshopper
58004036705b8b2c95d831a9e7c03f68593dde72
[ "MIT" ]
152
2020-10-02T12:05:11.000Z
2021-10-10T05:49:59.000Z
#pragma once #include <algorithm> #include <functional> #include <iostream> #include <map> #include <vector> #include "../domain/exceptions.h" template <typename ElementType> class Repo { private: /** * Ensures that the given element is not already in repo * * @param element The element to be validated * @throws Exception if element already in repo */ virtual void ValidateDuplicate(ElementType const &element) = 0; /** * Ensures that the given element is existent in repo * * @param element The element to be validated * @throws Exception if element is not in repo */ virtual void ValidateExistance(ElementType const &element) = 0; /** * Ensures that the given key is valid * * @param index The index to be validated * @throws Exception if index is out of bounds or not the correct type */ virtual void ValidateIndex(int const &index) = 0; public: // Repo constructor Repo() = default; // Repo destructor ~Repo() = default; /// Elements getter virtual std::map<int, ElementType> getElements() const = 0; /// Elements setter virtual void setElements(std::map<int, ElementType> const &value) = 0; /** * Overloading the subscripting operator * Gets the element at a given index * * @param index The index of the element to be returned from the repo * @returns The element at the index position */ virtual ElementType &operator[](int const &index) = 0; /** * Gets the length of the repo * * @returns Number of elements */ virtual int Size() const = 0; /** * Verifies the emptiness of the repo * * @returns True if list is empty of false otherwise */ virtual bool Empty() const = 0; /** * Swaps two elements * * @param first The firs element's index * @param second The second's element index * @throw Exception if first or secod index are out of bounds or equal */ virtual void Swap(int const &first, int const &second) = 0; /** * Adds element at the end of the repo * * @param element An element * @param validateDuplicate Should the function check for duplicate in repo? * @throws Exception if element already in repo */ virtual void Add(ElementType const &element, bool const &validateDuplicate = true) = 0; /** * Modifies an element at the given index * * @param index The position for modification * @param element The element to be modified * @throws Exception if index is not valid or if the modified element is already in repo */ virtual void Insert(int const &index, ElementType const &element) = 0; /** * Erases the element from the given position * * @param index The index of the element to be removed * @throws Exception if index is not valid */ virtual void Erase(int const &index) = 0; /** * Finds an element in the repo * * @param isMatching Function used for matching the element * @returns Iterator to the searched element * @throws Exception if repo is empty or element is not found */ virtual int FindIf(std::function<bool (ElementType)> const &isMatching) = 0; //DictRepo<ElementType>::Iterator FindIf(std::function<bool (ElementType)> const &isMatching); /** * Sorts the repo * * @param compareElements Element comparation function */ virtual void Sort(std::function<bool (ElementType, ElementType)> const &compareElements) = 0; /** * Returns the repo values in a stl vector * * @returns A stl vector with the repo values */ virtual std::vector<ElementType> toVector() = 0; }; template <typename ElementType> class DictRepo: public Repo<ElementType> { private: /// Implementation of stl vector for the repo std::map<int, ElementType> elements = std::map<int, ElementType>(); /** * Ensures that the given element is not already in repo * * @param element The element to be validated * @throws Exception if element already in repo */ void ValidateDuplicate(ElementType const &element); /** * Ensures that the given element is existent in repo * * @param element The element to be validated * @throws Exception if element is not in repo */ void ValidateExistance(ElementType const &element); /** * Ensures that the given key is valid * * @param index The index to be validated * @throws Exception if index is out of bounds or not the correct type */ void ValidateIndex(int const &index); public: /// DictRepo constructor DictRepo(); /// DictRepo destructor ~DictRepo(); /// Elements getter std::map<int, ElementType> getElements() const { return this->elements; } /// Elements setter void setElements(std::map<int, ElementType> const &value) { this->elements = value; } /** * Overloading the subscripting operator * Gets the element at a given index * * @param index The index of the element to be returned from the repo * @returns The element at the index position */ ElementType &operator[](int const &index); /** * Gets the length of the repo * * @returns Number of elements */ int Size() const; /** * Verifies the emptiness of the repo * * @returns True if list is empty of false otherwise */ bool Empty() const; /** * Swaps two elements * * @param first The firs element's index * @param second The second's element index * @throw Exception if first or secod index are out of bounds or equal */ void Swap(int const &first, int const &second); /** * Adds element at the end of the repo * * @param element An element * @param validateDuplicate Should the function check for duplicate in repo? * @throws Exception if element already in repo */ void Add(ElementType const &element, bool const &validateDuplicate = true); /** * Modifies an element at the given index * * @param index The position for modification * @param element The element to be modified * @throws Exception if index is not valid or if the modified element is already in repo */ void Insert(int const &index, ElementType const &element); /** * Erases the element from the given position * * @param index The index of the element to be removed * @throws Exception if index is not valid */ void Erase(int const &index); /** * Finds an element in the repo * * @param isMatching Function used for matching the element * @returns Iterator to the searched element * @throws Exception if repo is empty or element is not found */ int FindIf(std::function<bool (ElementType)> const &isMatching); //DictRepo<ElementType>::Iterator FindIf(std::function<bool (ElementType)> const &isMatching); /** * Sorts the repo * * @param compareElements Element comparation function */ void Sort(std::function<bool (ElementType, ElementType)> const &compareElements); /** * Returns the repo values in a stl vector * * @returns A stl vector with the repo values */ std::vector<ElementType> toVector(); }; template <typename ElementType> void DictRepo<ElementType>::ValidateDuplicate(ElementType const &element) { // search in all elements for (int i = 0; i < this->Size(); i++) // throw exception if element found if (this->operator[](i) == element) { throw DuplicateError("element already in repo\n"); } } template <typename ElementType> void DictRepo<ElementType>::ValidateExistance(ElementType const &element) { // search in all elements for (int i = 0; i < this->Size(); i++) // return if element found if (this->operator[](i) == element) { return; } // throw exception if element not found throw NotFoundError("element not found\n"); } template <typename ElementType> void DictRepo<ElementType>::ValidateIndex(int const &index) { // if empty repo throw exception if (this->Empty()) { throw EmptyRepoError("empty repo\n"); } // if index out of bounds throw exception if (index < 0 || index > this->Size() - 1) { throw IndexError("index out of bounds\n"); } } template <typename ElementType> DictRepo<ElementType>::DictRepo() { // init with empty container this->elements = std::map<int, ElementType>(); } template <typename ElementType> DictRepo<ElementType>::~DictRepo() { // set to default value (empty container) this->elements = std::map<int, ElementType>(); } template <typename ElementType> ElementType &DictRepo<ElementType>::operator[](int const &index) { // validate index this->ValidateIndex(index); // return the element at index location return this->elements[index]; } template <typename ElementType> int DictRepo<ElementType>::Size() const { // return the number of elements return this->elements.size(); } template <typename ElementType> bool DictRepo<ElementType>::Empty() const { // return the emptyness state of the container return this->elements.empty(); } template <typename ElementType> void DictRepo<ElementType>::Swap(int const &first, int const &second) { // validate first index this->ValidateIndex(first); // validate second index this->ValidateIndex(second); // if indexes are equal throw exception if (first == second) { throw IndexError("indexes are identical\n"); } // swap elements ElementType temp = this->elements[first]; this->elements[first] = this->elements[second]; this->elements[second] = temp; } template <typename ElementType> void DictRepo<ElementType>::Add(ElementType const &element, bool const &validateDuplicate) { // validate element if (validateDuplicate) { this->ValidateDuplicate(element); } // add element to end of repo this->elements[this->Size()] = element; } template <typename ElementType> void DictRepo<ElementType>::Insert(int const &index, ElementType const &element) { // validate index this->ValidateIndex(index); // validate element this->ValidateDuplicate(element); // shift elements to the right int end = this->Size(); for (int i = end; i > index; i--) this->elements[i] = this->elements[i - 1]; // insert element at index this->elements[index] = element; } template <typename ElementType> void DictRepo<ElementType>::Erase(int const &index) { // validate index this->ValidateIndex(index); // shift elements to the left int end = this->Size(); for (int i = index; i < end; i++) this->elements[i] = this->elements[i + 1]; // erase the last 2 elements because one was newly created when shifting this->elements.erase(this->Size() - 1); this->elements.erase(this->Size() - 1); } template <typename ElementType> int DictRepo<ElementType>::FindIf(std::function<bool(ElementType)> const &isMatching) { // validate repo emptyness if (this->Empty()) { throw EmptyRepoError("empty repo\n"); } // search the index of the wanted element for (int i = 0; i < this->Size(); i++) if (isMatching(this->elements[i])) return i; // if not found throw exception throw NotFoundError("element not found\n"); } template <typename ElementType> void DictRepo<ElementType>::Sort(std::function<bool (ElementType, ElementType)> const &compareElements) { // validate repo emptyness if (this->Empty()) { throw EmptyRepoError("empty repo\n"); } // sort the vector of values using the given compare function std::vector<ElementType> newVector = this->toVector(); std::sort(newVector.begin(), newVector.end(), compareElements); // replace the old values with the sorted ones for (int i = 0; i < this->Size(); i++) this->elements[i] = newVector[i]; } template <typename ElementType> std::vector<ElementType> DictRepo<ElementType>::toVector() { // make a new vector to store the values into std::vector<ElementType> newVector = std::vector<ElementType>(); // add all repo values in te vector for (int i = 0; i < this->Size(); i++) newVector.push_back(this->elements[i]); // retur the vector with the repo values return newVector; }
27.167431
103
0.6916
[ "vector" ]
e47e3832693f2adbbcaa7d809bd921a09a2867fd
2,595
h
C
geode/utility/endian.h
Haider-BA/geode
b9ebbc0c61acd17ceb21200dba0d52546a3dbff2
[ "BSD-3-Clause" ]
1
2021-06-19T13:12:35.000Z
2021-06-19T13:12:35.000Z
geode/utility/endian.h
Haider-BA/geode
b9ebbc0c61acd17ceb21200dba0d52546a3dbff2
[ "BSD-3-Clause" ]
null
null
null
geode/utility/endian.h
Haider-BA/geode
b9ebbc0c61acd17ceb21200dba0d52546a3dbff2
[ "BSD-3-Clause" ]
null
null
null
// Endianness detections and conversion #pragma once #include <geode/utility/config.h> #ifdef __APPLE__ #include <sys/types.h> #else #include <endian.h> #endif namespace geode { // How to detect endianness: // // #if GEODE_ENDIAN == GEODE_LITTLE_ENDIAN // if (GEODE_ENDIAN == GEODE_LITTLE_ENDIAN) #define GEODE_LITTLE_ENDIAN 1 #define GEODE_BIG_ENDIAN 2 #ifdef __APPLE__ # if BYTE_ORDER == LITTLE_ENDIAN # define GEODE_ENDIAN GEODE_LITTLE_ENDIAN # elif BYTE_ORDER == BIG_ENDIAN # define GEODE_ENDIAN GEODE_BIG_ENDIAN # else # error Unknown machine endianness # endif #else # if __BYTE_ORDER == __LITTLE_ENDIAN # define GEODE_ENDIAN GEODE_LITTLE_ENDIAN # elif __BYTE_ORDER == __BIG_ENDIAN # define GEODE_ENDIAN GEODE_BIG_ENDIAN # else # error Unknown machine endianness # endif #endif // Handle unsigned ints specially static inline uint8_t flip_endian(uint8_t x) { return x; } static inline uint16_t flip_endian(uint16_t x) { return x<<8|x>>8; } static inline uint32_t flip_endian(uint32_t x) { const uint32_t lo = 0x00ff00ff; x = (x&lo)<<8|(x>>8&lo); x = x<<16|x>>16; return x; } static inline uint64_t flip_endian(uint64_t x) { const uint64_t lo1 = 0x00ff00ff00ff00ff, lo2 = 0x0000ffff0000ffff; x = (x&lo1)<<8|(x>>8&lo1); x = (x&lo2)<<16|(x>>16&lo2); x = x<<32|x>>32; return x; } // Vectors flip componentwise template<class T,int d> static inline Vector<T,d> flip_endian(const Vector<T,d>& v) { Vector<T,d> r; for (int i=0;i<d;i++) r[i] = flip_endian(v[i]); } // For everything else, use the int case template<class T> static inline T flip_endian(const T x) { const int n = sizeof(T); static_assert((n&(n-1))==0,"Size not a power of two"); typedef typename uint_t<8*n>::exact I; union { T x; I i; } u; u.x = x; u.i = flip_endian(u.i); return u.x; } // Convert to big or little endian #if GEODE_ENDIAN == GEODE_LITTLE_ENDIAN template<class T> static inline const T& to_little_endian(const T& x) { return x; } template<class T> static inline T to_big_endian (const T& x) { return flip_endian(x); } #elif GEODE_ENDIAN == GEODE_BIG_ENDIAN template<class T> static inline T to_little_endian(const T& x) { return flip_endian(x); } template<class T> static inline const T& to_big_endian (const T& x) { return x; } #endif // Same as to_, but useful for documentation purposes template<class T> static inline T from_little_endian(const T& x) { return to_little_endian(x); } template<class T> static inline T from_big_endian (const T& x) { return to_big_endian(x); } }
25.693069
96
0.697881
[ "vector" ]
e4a1106f34d77031e07104824a7de6de47fcff5e
69,761
h
C
stack/include/btm_api_types.h
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/include/btm_api_types.h
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
null
null
null
stack/include/btm_api_types.h
digi-embedded/android_platform_system_bt
635ddc5671274697ecfc9d4d44881f23d73a4cd0
[ "Apache-2.0" ]
2
2019-05-30T08:37:28.000Z
2019-10-01T16:39:33.000Z
/****************************************************************************** * * Copyright (C) 1999-2012 Broadcom 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. * ******************************************************************************/ #ifndef BTM_API_TYPES_H #define BTM_API_TYPES_H #include "bt_target.h" #include "device/include/esco_parameters.h" #include "hcidefs.h" #include "smp_api_types.h" /* Maximum number of bytes allowed for vendor specific command parameters */ #define BTM_MAX_VENDOR_SPECIFIC_LEN HCI_COMMAND_SIZE /* BTM application return status codes */ enum { BTM_SUCCESS = 0, /* 0 Command succeeded */ BTM_CMD_STARTED, /* 1 Command started OK. */ BTM_BUSY, /* 2 Device busy with another command */ BTM_NO_RESOURCES, /* 3 No resources to issue command */ BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */ BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */ BTM_WRONG_MODE, /* 6 Device in wrong mode for request */ BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */ BTM_DEVICE_TIMEOUT, /* 8 Device timeout */ BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */ BTM_ERR_PROCESSING, /* 10 Generic error */ BTM_NOT_AUTHORIZED, /* 11 Authorization failed */ BTM_DEV_RESET, /* 12 Device has been reset */ BTM_CMD_STORED, /* 13 request is stored in control block */ BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */ BTM_DELAY_CHECK, /* 15 delay the check on encryption */ BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */ BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */ BTM_FAILED_ON_SECURITY, /* 18 security failed */ BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */ BTM_MODE4_LEVEL4_NOT_SUPPORTED, /* 20 Secure Connections Only Mode can't be supported */ BTM_DEV_BLACKLISTED /* 21 The device is Blacklisted */ }; typedef uint8_t tBTM_STATUS; #if (BTA_HOST_INTERLEAVE_SEARCH == TRUE) typedef enum { BTM_BR_ONE, /*0 First state or BR/EDR scan 1*/ BTM_BLE_ONE, /*1BLE scan 1*/ BTM_BR_TWO, /*2 BR/EDR scan 2*/ BTM_BLE_TWO, /*3 BLE scan 2*/ BTM_FINISH, /*4 End of Interleave Scan, or normal scan*/ BTM_NO_INTERLEAVING /*5 No Interleaving*/ } btm_inq_state; #endif /************************* * Device Control Types *************************/ #define BTM_DEVICE_ROLE_BR 0x01 #define BTM_DEVICE_ROLE_DUAL 0x02 #define BTM_MAX_DEVICE_ROLE BTM_DEVICE_ROLE_DUAL typedef uint8_t tBTM_DEVICE_ROLE; /* Device name of peer (may be truncated to save space in BTM database) */ typedef uint8_t tBTM_BD_NAME[BTM_MAX_REM_BD_NAME_LEN + 1]; /* Structure returned with local version information */ typedef struct { uint8_t hci_version; uint16_t hci_revision; uint8_t lmp_version; uint16_t manufacturer; uint16_t lmp_subversion; } tBTM_VERSION_INFO; /* Structure returned with Vendor Specific Command complete callback */ typedef struct { uint16_t opcode; uint16_t param_len; uint8_t* p_param_buf; } tBTM_VSC_CMPL; #define BTM_VSC_CMPL_DATA_SIZE \ (BTM_MAX_VENDOR_SPECIFIC_LEN + sizeof(tBTM_VSC_CMPL)) /************************************************** * Device Control and General Callback Functions **************************************************/ /* Callback function for when device status changes. Appl must poll for * what the new state is (BTM_IsDeviceUp). The event occurs whenever the stack * has detected that the controller status has changed. This asynchronous event * is enabled/disabled by calling BTM_RegisterForDeviceStatusNotif(). */ enum { BTM_DEV_STATUS_UP, BTM_DEV_STATUS_DOWN, BTM_DEV_STATUS_CMD_TOUT }; typedef uint8_t tBTM_DEV_STATUS; typedef void(tBTM_DEV_STATUS_CB)(tBTM_DEV_STATUS status); /* Callback function for when a vendor specific event occurs. The length and * array of returned parameter bytes are included. This asynchronous event * is enabled/disabled by calling BTM_RegisterForVSEvents(). */ typedef void(tBTM_VS_EVT_CB)(uint8_t len, uint8_t* p); /* General callback function for notifying an application that a synchronous * BTM function is complete. The pointer contains the address of any returned * data. */ typedef void(tBTM_CMPL_CB)(void* p1); /* VSC callback function for notifying an application that a synchronous * BTM function is complete. The pointer contains the address of any returned * data. */ typedef void(tBTM_VSC_CMPL_CB)(tBTM_VSC_CMPL* p1); /* Callback for apps to check connection and inquiry filters. * Parameters are the BD Address of remote and the Dev Class of remote. If the * app returns none zero, the connection or inquiry result will be dropped. */ typedef uint8_t(tBTM_FILTER_CB)(BD_ADDR bd_addr, DEV_CLASS dc); /***************************************************************************** * DEVICE DISCOVERY - Inquiry, Remote Name, Discovery, Class of Device ****************************************************************************/ /******************************* * Device Discovery Constants *******************************/ /* Discoverable modes */ #define BTM_NON_DISCOVERABLE 0 #define BTM_LIMITED_DISCOVERABLE 1 #define BTM_GENERAL_DISCOVERABLE 2 #define BTM_DISCOVERABLE_MASK \ (BTM_LIMITED_DISCOVERABLE | BTM_GENERAL_DISCOVERABLE) #define BTM_MAX_DISCOVERABLE BTM_GENERAL_DISCOVERABLE /* high byte for BLE Discoverable modes */ #define BTM_BLE_NON_DISCOVERABLE 0x0000 #define BTM_BLE_LIMITED_DISCOVERABLE 0x0100 #define BTM_BLE_GENERAL_DISCOVERABLE 0x0200 #define BTM_BLE_MAX_DISCOVERABLE BTM_BLE_GENERAL_DISCOVERABLE #define BTM_BLE_DISCOVERABLE_MASK \ (BTM_BLE_NON_DISCOVERABLE | BTM_BLE_LIMITED_DISCOVERABLE | \ BTM_BLE_GENERAL_DISCOVERABLE) /* Connectable modes */ #define BTM_NON_CONNECTABLE 0 #define BTM_CONNECTABLE 1 #define BTM_CONNECTABLE_MASK (BTM_NON_CONNECTABLE | BTM_CONNECTABLE) /* high byte for BLE Connectable modes */ #define BTM_BLE_NON_CONNECTABLE 0x0000 #define BTM_BLE_CONNECTABLE 0x0100 #define BTM_BLE_MAX_CONNECTABLE BTM_BLE_CONNECTABLE #define BTM_BLE_CONNECTABLE_MASK (BTM_BLE_NON_CONNECTABLE | BTM_BLE_CONNECTABLE) /* Inquiry modes * Note: These modes are associated with the inquiry active values (BTM_*ACTIVE) */ #define BTM_INQUIRY_NONE 0 #define BTM_GENERAL_INQUIRY 0x01 #define BTM_LIMITED_INQUIRY 0x02 #define BTM_BR_INQUIRY_MASK (BTM_GENERAL_INQUIRY | BTM_LIMITED_INQUIRY) /* high byte of inquiry mode for BLE inquiry mode */ #define BTM_BLE_INQUIRY_NONE 0x00 #define BTM_BLE_GENERAL_INQUIRY 0x10 #define BTM_BLE_LIMITED_INQUIRY 0x20 #define BTM_BLE_INQUIRY_MASK (BTM_BLE_GENERAL_INQUIRY | BTM_BLE_LIMITED_INQUIRY) /* BTM_IsInquiryActive return values (Bit Mask) * Note: These bit masks are associated with the inquiry modes (BTM_*_INQUIRY) */ /* no inquiry in progress */ #define BTM_INQUIRY_INACTIVE 0x0 /* a general inquiry is in progress */ #define BTM_GENERAL_INQUIRY_ACTIVE BTM_GENERAL_INQUIRY /* a limited inquiry is in progress */ #define BTM_LIMITED_INQUIRY_ACTIVE BTM_LIMITED_INQUIRY /* a periodic inquiry is active */ #define BTM_PERIODIC_INQUIRY_ACTIVE 0x8 /* SSP is active, so inquiry is disallowed (work around for FW bug) */ #define BTM_SSP_INQUIRY_ACTIVE 0x4 /* a general inquiry is in progress */ #define BTM_LE_GENERAL_INQUIRY_ACTIVE BTM_BLE_GENERAL_INQUIRY /* a limited inquiry is in progress */ #define BTM_LE_LIMITED_INQUIRY_ACTIVE BTM_BLE_LIMITED_INQUIRY /* inquiry activity mask */ /* BR/EDR inquiry activity mask */ #define BTM_BR_INQ_ACTIVE_MASK \ (BTM_GENERAL_INQUIRY_ACTIVE | BTM_LIMITED_INQUIRY_ACTIVE | \ BTM_PERIODIC_INQUIRY_ACTIVE) /* LE scan activity mask */ #define BTM_BLE_SCAN_ACTIVE_MASK 0xF0 /* LE inquiry activity mask*/ #define BTM_BLE_INQ_ACTIVE_MASK \ (BTM_LE_GENERAL_INQUIRY_ACTIVE | BTM_LE_LIMITED_INQUIRY_ACTIVE) /* inquiry activity mask */ #define BTM_INQUIRY_ACTIVE_MASK \ (BTM_BR_INQ_ACTIVE_MASK | BTM_BLE_INQ_ACTIVE_MASK) /* Define scan types */ #define BTM_SCAN_TYPE_STANDARD 0 #define BTM_SCAN_TYPE_INTERLACED 1 /* 1.2 devices only */ /* Define inquiry results mode */ #define BTM_INQ_RESULT_STANDARD 0 #define BTM_INQ_RESULT_WITH_RSSI 1 #define BTM_INQ_RESULT_EXTENDED 2 /* RSSI value not supplied (ignore it) */ #define BTM_INQ_RES_IGNORE_RSSI 0x7f /* Inquiry Filter Condition types (see tBTM_INQ_PARMS) */ /* Inquiry Filtering is turned off */ #define BTM_CLR_INQUIRY_FILTER 0 /* Filter on device class */ #define BTM_FILTER_COND_DEVICE_CLASS HCI_FILTER_COND_DEVICE_CLASS /* Filter on device addr */ #define BTM_FILTER_COND_BD_ADDR HCI_FILTER_COND_BD_ADDR /* State of the remote name retrieval during inquiry operations. * Used in the tBTM_INQ_INFO structure, and returned in the * BTM_InqDbRead, BTM_InqDbFirst, and BTM_InqDbNext functions. * The name field is valid when the state returned is * BTM_INQ_RMT_NAME_DONE */ #define BTM_INQ_RMT_NAME_EMPTY 0 #define BTM_INQ_RMT_NAME_PENDING 1 #define BTM_INQ_RMT_NAME_DONE 2 #define BTM_INQ_RMT_NAME_FAILED 3 /********************************* *** Class of Device constants *** *********************************/ #define BTM_FORMAT_TYPE_1 0x00 /**************************** * minor device class field ****************************/ /* 0x00 is used as unclassified for all minor device classes */ #define BTM_COD_MINOR_UNCLASSIFIED 0x00 /* minor device class field for Computer Major Class */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ #define BTM_COD_MINOR_DESKTOP_WORKSTATION 0x04 #define BTM_COD_MINOR_SERVER_COMPUTER 0x08 #define BTM_COD_MINOR_LAPTOP 0x0C #define BTM_COD_MINOR_HANDHELD_PC_PDA 0x10 /* clam shell */ #define BTM_COD_MINOR_PALM_SIZE_PC_PDA 0x14 #define BTM_COD_MINOR_WEARABLE_COMPUTER 0x18 /* watch sized */ /* minor device class field for Phone Major Class */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ #define BTM_COD_MINOR_CELLULAR 0x04 #define BTM_COD_MINOR_CORDLESS 0x08 #define BTM_COD_MINOR_SMART_PHONE 0x0C /* wired modem or voice gatway */ #define BTM_COD_MINOR_WIRED_MDM_V_GTWY 0x10 #define BTM_COD_MINOR_ISDN_ACCESS 0x14 /* minor device class field for LAN Access Point Major Class */ /* Load Factor Field bit 5-7 */ #define BTM_COD_MINOR_FULLY_AVAILABLE 0x00 #define BTM_COD_MINOR_1_17_UTILIZED 0x20 #define BTM_COD_MINOR_17_33_UTILIZED 0x40 #define BTM_COD_MINOR_33_50_UTILIZED 0x60 #define BTM_COD_MINOR_50_67_UTILIZED 0x80 #define BTM_COD_MINOR_67_83_UTILIZED 0xA0 #define BTM_COD_MINOR_83_99_UTILIZED 0xC0 #define BTM_COD_MINOR_NO_SERVICE_AVAILABLE 0xE0 /* sub-Field bit 2-4 */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ /* minor device class field for Audio/Video Major Class */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ #define BTM_COD_MINOR_CONFM_HEADSET 0x04 #define BTM_COD_MINOR_CONFM_HANDSFREE 0x08 #define BTM_COD_MINOR_MICROPHONE 0x10 #define BTM_COD_MINOR_LOUDSPEAKER 0x14 #define BTM_COD_MINOR_HEADPHONES 0x18 #define BTM_COD_MINOR_PORTABLE_AUDIO 0x1C #define BTM_COD_MINOR_CAR_AUDIO 0x20 #define BTM_COD_MINOR_SET_TOP_BOX 0x24 #define BTM_COD_MINOR_HIFI_AUDIO 0x28 #define BTM_COD_MINOR_VCR 0x2C #define BTM_COD_MINOR_VIDEO_CAMERA 0x30 #define BTM_COD_MINOR_CAMCORDER 0x34 #define BTM_COD_MINOR_VIDEO_MONITOR 0x38 #define BTM_COD_MINOR_VIDDISP_LDSPKR 0x3C #define BTM_COD_MINOR_VIDEO_CONFERENCING 0x40 #define BTM_COD_MINOR_GAMING_TOY 0x48 /* minor device class field for Peripheral Major Class */ /* Bits 6-7 independently specify mouse, keyboard, or combo mouse/keyboard */ #define BTM_COD_MINOR_KEYBOARD 0x40 #define BTM_COD_MINOR_POINTING 0x80 #define BTM_COD_MINOR_COMBO 0xC0 /* Bits 2-5 OR'd with selection from bits 6-7 */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ #define BTM_COD_MINOR_JOYSTICK 0x04 #define BTM_COD_MINOR_GAMEPAD 0x08 #define BTM_COD_MINOR_REMOTE_CONTROL 0x0C #define BTM_COD_MINOR_SENSING_DEVICE 0x10 #define BTM_COD_MINOR_DIGITIZING_TABLET 0x14 #define BTM_COD_MINOR_CARD_READER 0x18 /* e.g. SIM card reader */ #define BTM_COD_MINOR_DIGITAL_PAN 0x1C #define BTM_COD_MINOR_HAND_SCANNER 0x20 #define BTM_COD_MINOR_HAND_GESTURAL_INPUT 0x24 /* minor device class field for Imaging Major Class */ /* Bits 5-7 independently specify display, camera, scanner, or printer */ #define BTM_COD_MINOR_DISPLAY 0x10 #define BTM_COD_MINOR_CAMERA 0x20 #define BTM_COD_MINOR_SCANNER 0x40 #define BTM_COD_MINOR_PRINTER 0x80 /* Bits 2-3 Reserved */ /* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */ /* minor device class field for Wearable Major Class */ /* Bits 2-7 meaningful */ #define BTM_COD_MINOR_WRIST_WATCH 0x04 #define BTM_COD_MINOR_PAGER 0x08 #define BTM_COD_MINOR_JACKET 0x0C #define BTM_COD_MINOR_HELMET 0x10 #define BTM_COD_MINOR_GLASSES 0x14 /* minor device class field for Toy Major Class */ /* Bits 2-7 meaningful */ #define BTM_COD_MINOR_ROBOT 0x04 #define BTM_COD_MINOR_VEHICLE 0x08 #define BTM_COD_MINOR_DOLL_ACTION_FIGURE 0x0C #define BTM_COD_MINOR_CONTROLLER 0x10 #define BTM_COD_MINOR_GAME 0x14 /* minor device class field for Health Major Class */ /* Bits 2-7 meaningful */ #define BTM_COD_MINOR_BLOOD_MONITOR 0x04 #define BTM_COD_MINOR_THERMOMETER 0x08 #define BTM_COD_MINOR_WEIGHING_SCALE 0x0C #define BTM_COD_MINOR_GLUCOSE_METER 0x10 #define BTM_COD_MINOR_PULSE_OXIMETER 0x14 #define BTM_COD_MINOR_HEART_PULSE_MONITOR 0x18 #define BTM_COD_MINOR_HEALTH_DATA_DISPLAY 0x1C #define BTM_COD_MINOR_STEP_COUNTER 0x20 #define BTM_COD_MINOR_BODY_COM_ANALYZER 0x24 #define BTM_COD_MINOR_PEAK_FLOW_MONITOR 0x28 #define BTM_COD_MINOR_MEDICATION_MONITOR 0x2C #define BTM_COD_MINOR_KNEE_PROSTHESIS 0x30 #define BTM_COD_MINOR_ANKLE_PROSTHESIS 0x34 /*************************** * major device class field ***************************/ #define BTM_COD_MAJOR_MISCELLANEOUS 0x00 #define BTM_COD_MAJOR_COMPUTER 0x01 #define BTM_COD_MAJOR_PHONE 0x02 #define BTM_COD_MAJOR_LAN_ACCESS_PT 0x03 #define BTM_COD_MAJOR_AUDIO 0x04 #define BTM_COD_MAJOR_PERIPHERAL 0x05 #define BTM_COD_MAJOR_IMAGING 0x06 #define BTM_COD_MAJOR_WEARABLE 0x07 #define BTM_COD_MAJOR_TOY 0x08 #define BTM_COD_MAJOR_HEALTH 0x09 #define BTM_COD_MAJOR_UNCLASSIFIED 0x1F /*************************** * service class fields ***************************/ #define BTM_COD_SERVICE_LMTD_DISCOVER 0x0020 #define BTM_COD_SERVICE_POSITIONING 0x0100 #define BTM_COD_SERVICE_NETWORKING 0x0200 #define BTM_COD_SERVICE_RENDERING 0x0400 #define BTM_COD_SERVICE_CAPTURING 0x0800 #define BTM_COD_SERVICE_OBJ_TRANSFER 0x1000 #define BTM_COD_SERVICE_AUDIO 0x2000 #define BTM_COD_SERVICE_TELEPHONY 0x4000 #define BTM_COD_SERVICE_INFORMATION 0x8000 /* class of device field macros */ #define BTM_COD_FORMAT_TYPE(u8, pd) \ { (u8) = (pd)[2] & 0x03; } #define BTM_COD_MINOR_CLASS(u8, pd) \ { (u8) = (pd)[2] & 0xFC; } #define BTM_COD_MAJOR_CLASS(u8, pd) \ { (u8) = (pd)[1] & 0x1F; } #define BTM_COD_SERVICE_CLASS(u16, pd) \ { \ (u16) = (pd)[0]; \ (u16) <<= 8; \ (u16) += (pd)[1] & 0xE0; \ } /* to set the fields (assumes that format type is always 0) */ #define FIELDS_TO_COD(pd, mn, mj, sv) \ { \ (pd)[2] = mn; \ (pd)[1] = (mj) + ((sv)&BTM_COD_SERVICE_CLASS_LO_B); \ (pd)[0] = (sv) >> 8; \ } /* the COD masks */ #define BTM_COD_FORMAT_TYPE_MASK 0x03 #define BTM_COD_MINOR_CLASS_MASK 0xFC #define BTM_COD_MAJOR_CLASS_MASK 0x1F #define BTM_COD_SERVICE_CLASS_LO_B 0x00E0 #define BTM_COD_SERVICE_CLASS_MASK 0xFFE0 /* BTM service definitions * Used for storing EIR data to bit mask */ enum { BTM_EIR_UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER, /* BTM_EIR_UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR, */ /* BTM_EIR_UUID_SERVCLASS_PUBLIC_BROWSE_GROUP, */ BTM_EIR_UUID_SERVCLASS_SERIAL_PORT, BTM_EIR_UUID_SERVCLASS_LAN_ACCESS_USING_PPP, BTM_EIR_UUID_SERVCLASS_DIALUP_NETWORKING, BTM_EIR_UUID_SERVCLASS_IRMC_SYNC, BTM_EIR_UUID_SERVCLASS_OBEX_OBJECT_PUSH, BTM_EIR_UUID_SERVCLASS_OBEX_FILE_TRANSFER, BTM_EIR_UUID_SERVCLASS_IRMC_SYNC_COMMAND, BTM_EIR_UUID_SERVCLASS_HEADSET, BTM_EIR_UUID_SERVCLASS_CORDLESS_TELEPHONY, BTM_EIR_UUID_SERVCLASS_AUDIO_SOURCE, BTM_EIR_UUID_SERVCLASS_AUDIO_SINK, BTM_EIR_UUID_SERVCLASS_AV_REM_CTRL_TARGET, /* BTM_EIR_UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, */ BTM_EIR_UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING, */ BTM_EIR_UUID_SERVCLASS_INTERCOM, BTM_EIR_UUID_SERVCLASS_FAX, BTM_EIR_UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTM_EIR_UUID_SERVCLASS_WAP, */ /* BTM_EIR_UUID_SERVCLASS_WAP_CLIENT, */ BTM_EIR_UUID_SERVCLASS_PANU, BTM_EIR_UUID_SERVCLASS_NAP, BTM_EIR_UUID_SERVCLASS_GN, BTM_EIR_UUID_SERVCLASS_DIRECT_PRINTING, /* BTM_EIR_UUID_SERVCLASS_REFERENCE_PRINTING, */ BTM_EIR_UUID_SERVCLASS_IMAGING, BTM_EIR_UUID_SERVCLASS_IMAGING_RESPONDER, BTM_EIR_UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE, BTM_EIR_UUID_SERVCLASS_IMAGING_REF_OBJECTS, BTM_EIR_UUID_SERVCLASS_HF_HANDSFREE, BTM_EIR_UUID_SERVCLASS_AG_HANDSFREE, BTM_EIR_UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE, /* BTM_EIR_UUID_SERVCLASS_REFLECTED_UI, */ BTM_EIR_UUID_SERVCLASS_BASIC_PRINTING, BTM_EIR_UUID_SERVCLASS_PRINTING_STATUS, BTM_EIR_UUID_SERVCLASS_HUMAN_INTERFACE, BTM_EIR_UUID_SERVCLASS_CABLE_REPLACEMENT, BTM_EIR_UUID_SERVCLASS_HCRP_PRINT, BTM_EIR_UUID_SERVCLASS_HCRP_SCAN, /* BTM_EIR_UUID_SERVCLASS_COMMON_ISDN_ACCESS, */ /* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING_GW, */ /* BTM_EIR_UUID_SERVCLASS_UDI_MT, */ /* BTM_EIR_UUID_SERVCLASS_UDI_TA, */ /* BTM_EIR_UUID_SERVCLASS_VCP, */ BTM_EIR_UUID_SERVCLASS_SAP, BTM_EIR_UUID_SERVCLASS_PBAP_PCE, BTM_EIR_UUID_SERVCLASS_PBAP_PSE, /* BTM_EIR_UUID_SERVCLASS_TE_PHONE_ACCESS, */ /* BTM_EIR_UUID_SERVCLASS_ME_PHONE_ACCESS, */ BTM_EIR_UUID_SERVCLASS_PHONE_ACCESS, BTM_EIR_UUID_SERVCLASS_HEADSET_HS, BTM_EIR_UUID_SERVCLASS_PNP_INFORMATION, /* BTM_EIR_UUID_SERVCLASS_GENERIC_NETWORKING, */ /* BTM_EIR_UUID_SERVCLASS_GENERIC_FILETRANSFER, */ /* BTM_EIR_UUID_SERVCLASS_GENERIC_AUDIO, */ /* BTM_EIR_UUID_SERVCLASS_GENERIC_TELEPHONY, */ /* BTM_EIR_UUID_SERVCLASS_UPNP_SERVICE, */ /* BTM_EIR_UUID_SERVCLASS_UPNP_IP_SERVICE, */ /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_PAN, */ /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_LAP, */ /* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP, */ BTM_EIR_UUID_SERVCLASS_VIDEO_SOURCE, BTM_EIR_UUID_SERVCLASS_VIDEO_SINK, /* BTM_EIR_UUID_SERVCLASS_VIDEO_DISTRIBUTION */ /* BTM_EIR_UUID_SERVCLASS_HDP_PROFILE */ BTM_EIR_UUID_SERVCLASS_MESSAGE_ACCESS, BTM_EIR_UUID_SERVCLASS_MESSAGE_NOTIFICATION, BTM_EIR_UUID_SERVCLASS_HDP_SOURCE, BTM_EIR_UUID_SERVCLASS_HDP_SINK, BTM_EIR_MAX_SERVICES }; /* search result in EIR of inquiry database */ #define BTM_EIR_FOUND 0 #define BTM_EIR_NOT_FOUND 1 #define BTM_EIR_UNKNOWN 2 typedef uint8_t tBTM_EIR_SEARCH_RESULT; /* 0x01 */ #define BTM_EIR_FLAGS_TYPE HCI_EIR_FLAGS_TYPE /* 0x02 */ #define BTM_EIR_MORE_16BITS_UUID_TYPE HCI_EIR_MORE_16BITS_UUID_TYPE /* 0x03 */ #define BTM_EIR_COMPLETE_16BITS_UUID_TYPE HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x04 */ #define BTM_EIR_MORE_32BITS_UUID_TYPE HCI_EIR_MORE_32BITS_UUID_TYPE /* 0x05 */ #define BTM_EIR_COMPLETE_32BITS_UUID_TYPE HCI_EIR_COMPLETE_32BITS_UUID_TYPE /* 0x06 */ #define BTM_EIR_MORE_128BITS_UUID_TYPE HCI_EIR_MORE_128BITS_UUID_TYPE /* 0x07 */ #define BTM_EIR_COMPLETE_128BITS_UUID_TYPE HCI_EIR_COMPLETE_128BITS_UUID_TYPE /* 0x08 */ #define BTM_EIR_SHORTENED_LOCAL_NAME_TYPE HCI_EIR_SHORTENED_LOCAL_NAME_TYPE /* 0x09 */ #define BTM_EIR_COMPLETE_LOCAL_NAME_TYPE HCI_EIR_COMPLETE_LOCAL_NAME_TYPE /* 0x0A */ #define BTM_EIR_TX_POWER_LEVEL_TYPE HCI_EIR_TX_POWER_LEVEL_TYPE /* 0xFF */ #define BTM_EIR_MANUFACTURER_SPECIFIC_TYPE HCI_EIR_MANUFACTURER_SPECIFIC_TYPE /* the following EIR tags are defined to OOB, not regular EIR data */ /* 6 bytes */ #define BTM_EIR_OOB_BD_ADDR_TYPE HCI_EIR_OOB_BD_ADDR_TYPE /* 3 bytes */ #define BTM_EIR_OOB_COD_TYPE HCI_EIR_OOB_COD_TYPE /* 16 bytes */ #define BTM_EIR_OOB_SSP_HASH_C_TYPE HCI_EIR_OOB_SSP_HASH_C_TYPE /* 16 bytes */ #define BTM_EIR_OOB_SSP_RAND_R_TYPE HCI_EIR_OOB_SSP_RAND_R_TYPE /* include 2 bytes length & 6 bytes bd_addr */ #define BTM_OOB_MANDATORY_SIZE 8 #define BTM_OOB_DATA_LEN_SIZE 2 #define BTM_OOB_BD_ADDR_SIZE 6 #define BTM_OOB_COD_SIZE BT_OOB_COD_SIZE #define BTM_OOB_HASH_C_SIZE BT_OOB_HASH_C_SIZE #define BTM_OOB_RAND_R_SIZE BT_OOB_RAND_R_SIZE #define BTM_BLE_SEC_NONE 0 /* encrypt the link using current key */ #define BTM_BLE_SEC_ENCRYPT 1 #define BTM_BLE_SEC_ENCRYPT_NO_MITM 2 #define BTM_BLE_SEC_ENCRYPT_MITM 3 typedef uint8_t tBTM_BLE_SEC_ACT; /******************************************************************************* * BTM Services MACROS handle array of uint32_t bits for more than 32 services ******************************************************************************/ /* Determine the number of uint32_t's necessary for services */ #define BTM_EIR_ARRAY_BITS 32 /* Number of bits in each array element */ #define BTM_EIR_SERVICE_ARRAY_SIZE \ (((uint32_t)BTM_EIR_MAX_SERVICES / BTM_EIR_ARRAY_BITS) + \ (((uint32_t)BTM_EIR_MAX_SERVICES % BTM_EIR_ARRAY_BITS) ? 1 : 0)) /* MACRO to set the service bit mask in a bit stream */ #define BTM_EIR_SET_SERVICE(p, service) \ (((uint32_t*)(p))[(((uint32_t)(service)) / BTM_EIR_ARRAY_BITS)] |= \ ((uint32_t)1 << (((uint32_t)(service)) % BTM_EIR_ARRAY_BITS))) /* MACRO to clear the service bit mask in a bit stream */ #define BTM_EIR_CLR_SERVICE(p, service) \ (((uint32_t*)(p))[(((uint32_t)(service)) / BTM_EIR_ARRAY_BITS)] &= \ ~((uint32_t)1 << (((uint32_t)(service)) % BTM_EIR_ARRAY_BITS))) /* MACRO to check the service bit mask in a bit stream */ #define BTM_EIR_HAS_SERVICE(p, service) \ ((((uint32_t*)(p))[(((uint32_t)(service)) / BTM_EIR_ARRAY_BITS)] & \ ((uint32_t)1 << (((uint32_t)(service)) % BTM_EIR_ARRAY_BITS))) >> \ (((uint32_t)(service)) % BTM_EIR_ARRAY_BITS)) /* start of EIR in HCI buffer, 4 bytes = HCI Command(2) + Length(1) + FEC_Req(1) */ #define BTM_HCI_EIR_OFFSET (BT_HDR_SIZE + 4) /*************************** * Device Discovery Types ***************************/ /* Definitions of the parameters passed to BTM_StartInquiry and * BTM_SetPeriodicInquiryMode. */ typedef struct /* contains the two device class condition fields */ { DEV_CLASS dev_class; DEV_CLASS dev_class_mask; } tBTM_COD_COND; typedef union /* contains the inquiry filter condition */ { BD_ADDR bdaddr_cond; tBTM_COD_COND cod_cond; } tBTM_INQ_FILT_COND; typedef struct /* contains the parameters passed to the inquiry functions */ { uint8_t mode; /* general or limited */ uint8_t duration; /* duration of the inquiry (1.28 sec increments) */ uint8_t max_resps; /* maximum number of responses to return */ bool report_dup; /* report duplicated inquiry response with higher RSSI value */ uint8_t filter_cond_type; /* new devices, BD ADDR, COD, or No filtering */ tBTM_INQ_FILT_COND filter_cond; /* filter value based on filter cond type */ #if (BTA_HOST_INTERLEAVE_SEARCH == TRUE) uint8_t intl_duration [4]; /*duration array storing the interleave scan's time portions*/ #endif } tBTM_INQ_PARMS; #define BTM_INQ_RESULT_BR 0x01 #define BTM_INQ_RESULT_BLE 0x02 constexpr uint8_t BLE_EVT_CONNECTABLE_BIT = 0; constexpr uint8_t BLE_EVT_SCANNABLE_BIT = 1; constexpr uint8_t BLE_EVT_DIRECTED_BIT = 2; constexpr uint8_t BLE_EVT_SCAN_RESPONSE_BIT = 3; constexpr uint8_t BLE_EVT_LEGACY_BIT = 4; constexpr uint8_t PHY_LE_NO_PACKET = 0x00; constexpr uint8_t PHY_LE_1M = 0x01; constexpr uint8_t PHY_LE_2M = 0x02; constexpr uint8_t PHY_LE_CODED = 0x03; constexpr uint8_t NO_ADI_PRESENT = 0xFF; constexpr uint8_t TX_POWER_NOT_PRESENT = 0x7F; /* These are the fields returned in each device's response to the inquiry. It * is returned in the results callback if registered. */ typedef struct { uint16_t clock_offset; BD_ADDR remote_bd_addr; DEV_CLASS dev_class; uint8_t page_scan_rep_mode; uint8_t page_scan_per_mode; uint8_t page_scan_mode; int8_t rssi; /* Set to BTM_INQ_RES_IGNORE_RSSI if not valid */ uint32_t eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE]; bool eir_complete_list; tBT_DEVICE_TYPE device_type; uint8_t inq_result_type; uint8_t ble_addr_type; uint16_t ble_evt_type; uint8_t ble_primary_phy; uint8_t ble_secondary_phy; uint8_t ble_advertising_sid; int8_t ble_tx_power; uint16_t ble_periodic_adv_int; uint8_t flag; } tBTM_INQ_RESULTS; /* This is the inquiry response information held in its database by BTM, and * available to applications via BTM_InqDbRead, BTM_InqDbFirst, and * BTM_InqDbNext. */ typedef struct { tBTM_INQ_RESULTS results; bool appl_knows_rem_name; /* set by application if it knows the remote name of the peer device. This is later used by application to determine if remote name request is required to be done. Having the flag here avoid duplicate store of inquiry results */ uint16_t remote_name_len; tBTM_BD_NAME remote_name; uint8_t remote_name_state; uint8_t remote_name_type; } tBTM_INQ_INFO; /* Structure returned with inquiry complete callback */ typedef struct { tBTM_STATUS status; uint8_t num_resp; /* Number of results from the current inquiry */ } tBTM_INQUIRY_CMPL; /* Structure returned with remote name request */ typedef struct { uint16_t status; BD_ADDR bd_addr; uint16_t length; BD_NAME remote_bd_name; } tBTM_REMOTE_DEV_NAME; typedef struct { uint8_t pcm_intf_rate; /* PCM interface rate: 0: 128kbps, 1: 256 kbps; 2:512 bps; 3: 1024kbps; 4: 2048kbps */ uint8_t frame_type; /* frame type: 0: short; 1: long */ uint8_t sync_mode; /* sync mode: 0: slave; 1: master */ uint8_t clock_mode; /* clock mode: 0: slave; 1: master */ } tBTM_SCO_PCM_PARAM; /**************************************** * Device Discovery Callback Functions ****************************************/ /* Callback function for asynchronous notifications when the BTM inquiry DB * changes. First param is inquiry database, second is if added to or removed * from the inquiry database. */ typedef void(tBTM_INQ_DB_CHANGE_CB)(void* p1, bool is_new); /* Callback function for notifications when the BTM gets inquiry response. * First param is inquiry results database, second is pointer of EIR. */ typedef void(tBTM_INQ_RESULTS_CB)(tBTM_INQ_RESULTS* p_inq_results, uint8_t* p_eir, uint16_t eir_len); /***************************************************************************** * ACL CHANNEL MANAGEMENT ****************************************************************************/ /****************** * ACL Constants ******************/ /* ACL modes */ #define BTM_ACL_MODE_NORMAL HCI_MODE_ACTIVE #define BTM_ACL_MODE_HOLD HCI_MODE_HOLD #define BTM_ACL_MODE_SNIFF HCI_MODE_SNIFF #define BTM_ACL_MODE_PARK HCI_MODE_PARK /* Returned with structure in role switch callback (tBTM_ROLE_SWITCH_CMPL) */ #define BTM_ROLE_MASTER HCI_ROLE_MASTER #define BTM_ROLE_SLAVE HCI_ROLE_SLAVE #define BTM_ROLE_UNDEFINED 0xff /* undefined value (error status) */ /* ACL Packet Types */ #define BTM_ACL_PKT_TYPES_MASK_DM1 HCI_PKT_TYPES_MASK_DM1 #define BTM_ACL_PKT_TYPES_MASK_DH1 HCI_PKT_TYPES_MASK_DH1 #define BTM_ACL_PKT_TYPES_MASK_DM3 HCI_PKT_TYPES_MASK_DM3 #define BTM_ACL_PKT_TYPES_MASK_DH3 HCI_PKT_TYPES_MASK_DH3 #define BTM_ACL_PKT_TYPES_MASK_DM5 HCI_PKT_TYPES_MASK_DM5 #define BTM_ACL_PKT_TYPES_MASK_DH5 HCI_PKT_TYPES_MASK_DH5 #define BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 HCI_PKT_TYPES_MASK_NO_2_DH1 #define BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 HCI_PKT_TYPES_MASK_NO_3_DH1 #define BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 HCI_PKT_TYPES_MASK_NO_2_DH3 #define BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 HCI_PKT_TYPES_MASK_NO_3_DH3 #define BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 HCI_PKT_TYPES_MASK_NO_2_DH5 #define BTM_ACL_PKT_TYPES_MASK_NO_3_DH5 HCI_PKT_TYPES_MASK_NO_3_DH5 /*************** * ACL Types ***************/ /* Structure returned with Role Switch information (in tBTM_CMPL_CB callback * function) in response to BTM_SwitchRole call. */ typedef struct { uint8_t hci_status; /* HCI status returned with the event */ uint8_t role; /* BTM_ROLE_MASTER or BTM_ROLE_SLAVE */ BD_ADDR remote_bd_addr; /* Remote BD addr involved with the switch */ } tBTM_ROLE_SWITCH_CMPL; /* Structure returned with QoS information (in tBTM_CMPL_CB callback function) * in response to BTM_SetQoS call. */ typedef struct { FLOW_SPEC flow; uint16_t handle; uint8_t status; } tBTM_QOS_SETUP_CMPL; /* Structure returned with read RSSI event (in tBTM_CMPL_CB callback function) * in response to BTM_ReadRSSI call. */ typedef struct { tBTM_STATUS status; uint8_t hci_status; int8_t rssi; BD_ADDR rem_bda; } tBTM_RSSI_RESULTS; /* Structure returned with read current TX power event (in tBTM_CMPL_CB callback * function) in response to BTM_ReadTxPower call. */ typedef struct { tBTM_STATUS status; uint8_t hci_status; int8_t tx_power; BD_ADDR rem_bda; } tBTM_TX_POWER_RESULTS; /* Structure returned with read link quality event (in tBTM_CMPL_CB callback * function) in response to BTM_ReadLinkQuality call. */ typedef struct { tBTM_STATUS status; uint8_t hci_status; uint8_t link_quality; BD_ADDR rem_bda; } tBTM_LINK_QUALITY_RESULTS; /* Structure returned with read inq tx power quality event (in tBTM_CMPL_CB * callback function) in response to BTM_ReadInquiryRspTxPower call. */ typedef struct { tBTM_STATUS status; uint8_t hci_status; int8_t tx_power; } tBTM_INQ_TXPWR_RESULTS; enum { BTM_BL_CONN_EVT, BTM_BL_DISCN_EVT, BTM_BL_UPDATE_EVT, BTM_BL_ROLE_CHG_EVT, BTM_BL_COLLISION_EVT }; typedef uint8_t tBTM_BL_EVENT; typedef uint16_t tBTM_BL_EVENT_MASK; #define BTM_BL_CONN_MASK 0x0001 #define BTM_BL_DISCN_MASK 0x0002 #define BTM_BL_UPDATE_MASK 0x0004 #define BTM_BL_ROLE_CHG_MASK 0x0008 /* Device features mask definitions */ #define BTM_FEATURE_BYTES_PER_PAGE HCI_FEATURE_BYTES_PER_PAGE #define BTM_EXT_FEATURES_PAGE_MAX HCI_EXT_FEATURES_PAGE_MAX /* the data type associated with BTM_BL_CONN_EVT */ typedef struct { tBTM_BL_EVENT event; /* The event reported. */ BD_ADDR_PTR p_bda; /* The address of the newly connected device */ DEV_CLASS_PTR p_dc; /* The device class */ BD_NAME_PTR p_bdn; /* The device name */ uint8_t* p_features; /* pointer to the remote device's features page[0] (supported features page) */ uint16_t handle; /* connection handle */ tBT_TRANSPORT transport; /* link is LE or not */ } tBTM_BL_CONN_DATA; /* the data type associated with BTM_BL_DISCN_EVT */ typedef struct { tBTM_BL_EVENT event; /* The event reported. */ BD_ADDR_PTR p_bda; /* The address of the disconnected device */ uint16_t handle; /* disconnected connection handle */ tBT_TRANSPORT transport; /* link is LE link or not */ } tBTM_BL_DISCN_DATA; /* Busy-Level shall have the inquiry_paging mask set when * inquiry/paging is in progress, Else the number of ACL links */ #define BTM_BL_INQUIRY_PAGING_MASK 0x10 #define BTM_BL_INQUIRY_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x1) #define BTM_BL_INQUIRY_CANCELLED (BTM_BL_INQUIRY_PAGING_MASK | 0x2) #define BTM_BL_INQUIRY_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x3) #define BTM_BL_PAGING_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x4) #define BTM_BL_PAGING_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x5) /* the data type associated with BTM_BL_UPDATE_EVT */ typedef struct { tBTM_BL_EVENT event; /* The event reported. */ uint8_t busy_level; /* when paging or inquiring, level is 10. * Otherwise, the number of ACL links. */ uint8_t busy_level_flags; /* Notifies actual inquiry/page activities */ } tBTM_BL_UPDATE_DATA; /* the data type associated with BTM_BL_ROLE_CHG_EVT */ typedef struct { tBTM_BL_EVENT event; /* The event reported. */ BD_ADDR_PTR p_bda; /* The address of the peer connected device */ uint8_t new_role; uint8_t hci_status; /* HCI status returned with the event */ } tBTM_BL_ROLE_CHG_DATA; typedef union { tBTM_BL_EVENT event; /* The event reported. */ tBTM_BL_CONN_DATA conn; /* The data associated with BTM_BL_CONN_EVT */ tBTM_BL_DISCN_DATA discn; /* The data associated with BTM_BL_DISCN_EVT */ tBTM_BL_UPDATE_DATA update; /* The data associated with BTM_BL_UPDATE_EVT */ tBTM_BL_ROLE_CHG_DATA role_chg; /*The data associated with BTM_BL_ROLE_CHG_EVT */ } tBTM_BL_EVENT_DATA; /* Callback function for notifications when the BTM busy level * changes. */ typedef void(tBTM_BL_CHANGE_CB)(tBTM_BL_EVENT_DATA* p_data); /*************************** * ACL Callback Functions ***************************/ /* Callback function for notifications when the BTM ACL connection DB * changes. First param is BD address, second is if added or removed. * Registered through BTM_AclRegisterForChanges call. */ typedef void(tBTM_ACL_DB_CHANGE_CB)(BD_ADDR p_bda, DEV_CLASS p_dc, BD_NAME p_bdn, uint8_t* features, bool is_new, uint16_t handle, tBT_TRANSPORT transport); /***************************************************************************** * SCO CHANNEL MANAGEMENT ****************************************************************************/ /****************** * SCO Constants ******************/ /* Define an invalid SCO index and an invalid HCI handle */ #define BTM_INVALID_SCO_INDEX 0xFFFF #define BTM_INVALID_HCI_HANDLE 0xFFFF /* Define an invalid SCO disconnect reason */ #define BTM_INVALID_SCO_DISC_REASON 0xFFFF /* Define first active SCO index */ #define BTM_FIRST_ACTIVE_SCO_INDEX BTM_MAX_SCO_LINKS #define BTM_SCO_LINK_ONLY_MASK \ (ESCO_PKT_TYPES_MASK_HV1 | ESCO_PKT_TYPES_MASK_HV2 | ESCO_PKT_TYPES_MASK_HV3) #define BTM_ESCO_LINK_ONLY_MASK \ (ESCO_PKT_TYPES_MASK_EV3 | ESCO_PKT_TYPES_MASK_EV4 | ESCO_PKT_TYPES_MASK_EV5) #define BTM_SCO_LINK_ALL_PKT_MASK \ (BTM_SCO_LINK_ONLY_MASK | BTM_ESCO_LINK_ONLY_MASK) #define BTM_VALID_SCO_ALL_PKT_TYPE HCI_VALID_SCO_ALL_PKT_TYPE /*************** * SCO Types ***************/ #define BTM_LINK_TYPE_SCO HCI_LINK_TYPE_SCO #define BTM_LINK_TYPE_ESCO HCI_LINK_TYPE_ESCO typedef uint8_t tBTM_SCO_TYPE; /******************* * SCO Codec Types *******************/ // TODO(google) This should use common definitions #define BTM_SCO_CODEC_NONE 0x0000 #define BTM_SCO_CODEC_CVSD 0x0001 #define BTM_SCO_CODEC_MSBC 0x0002 typedef uint16_t tBTM_SCO_CODEC_TYPE; /******************* * SCO Voice Settings *******************/ #define BTM_VOICE_SETTING_CVSD \ ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | \ HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_CVSD)) #define BTM_VOICE_SETTING_TRANS \ ((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | \ HCI_INP_SAMPLE_SIZE_16BIT | HCI_AIR_CODING_FORMAT_TRANSPNT)) /******************* * SCO Data Status *******************/ enum { BTM_SCO_DATA_CORRECT, BTM_SCO_DATA_PAR_ERR, BTM_SCO_DATA_NONE, BTM_SCO_DATA_PAR_LOST }; typedef uint8_t tBTM_SCO_DATA_FLAG; /*************************** * SCO Callback Functions ***************************/ typedef void(tBTM_SCO_CB)(uint16_t sco_inx); typedef void(tBTM_SCO_DATA_CB)(uint16_t sco_inx, BT_HDR* p_data, tBTM_SCO_DATA_FLAG status); /*************** * eSCO Types ***************/ /* tBTM_ESCO_CBACK event types */ #define BTM_ESCO_CHG_EVT 1 #define BTM_ESCO_CONN_REQ_EVT 2 typedef uint8_t tBTM_ESCO_EVT; /* Structure passed with SCO change command and events. * Used by both Sync and Enhanced sync messaging */ typedef struct { uint16_t max_latency_ms; uint16_t packet_types; uint8_t retransmission_effort; } tBTM_CHG_ESCO_PARAMS; /* Returned by BTM_ReadEScoLinkParms() */ typedef struct { uint16_t rx_pkt_len; uint16_t tx_pkt_len; BD_ADDR bd_addr; uint8_t link_type; /* BTM_LINK_TYPE_SCO or BTM_LINK_TYPE_ESCO */ uint8_t tx_interval; uint8_t retrans_window; uint8_t air_mode; } tBTM_ESCO_DATA; typedef struct { uint16_t sco_inx; uint16_t rx_pkt_len; uint16_t tx_pkt_len; BD_ADDR bd_addr; uint8_t hci_status; uint8_t tx_interval; uint8_t retrans_window; } tBTM_CHG_ESCO_EVT_DATA; typedef struct { uint16_t sco_inx; BD_ADDR bd_addr; DEV_CLASS dev_class; tBTM_SCO_TYPE link_type; } tBTM_ESCO_CONN_REQ_EVT_DATA; typedef union { tBTM_CHG_ESCO_EVT_DATA chg_evt; tBTM_ESCO_CONN_REQ_EVT_DATA conn_evt; } tBTM_ESCO_EVT_DATA; /*************************** * eSCO Callback Functions ***************************/ typedef void(tBTM_ESCO_CBACK)(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* p_data); /***************************************************************************** * SECURITY MANAGEMENT ****************************************************************************/ /******************************* * Security Manager Constants *******************************/ /* Security Mode (BTM_SetSecurityMode) */ #define BTM_SEC_MODE_UNDEFINED 0 #define BTM_SEC_MODE_NONE 1 #define BTM_SEC_MODE_SERVICE 2 #define BTM_SEC_MODE_LINK 3 #define BTM_SEC_MODE_SP 4 #define BTM_SEC_MODE_SP_DEBUG 5 #define BTM_SEC_MODE_SC 6 /* Maximum Number of BTM Security Modes */ #define BTM_SEC_MODES_MAX 7 /* Security Service Levels [bit mask] (BTM_SetSecurityLevel) * Encryption should not be used without authentication */ /* Nothing required */ #define BTM_SEC_NONE 0x0000 /* Inbound call requires authorization */ #define BTM_SEC_IN_AUTHORIZE 0x0001 /* Inbound call requires authentication */ #define BTM_SEC_IN_AUTHENTICATE 0x0002 /* Inbound call requires encryption */ #define BTM_SEC_IN_ENCRYPT 0x0004 /* Outbound call requires authorization */ #define BTM_SEC_OUT_AUTHORIZE 0x0008 /* Outbound call requires authentication */ #define BTM_SEC_OUT_AUTHENTICATE 0x0010 /* Outbound call requires encryption */ #define BTM_SEC_OUT_ENCRYPT 0x0020 /* Secure Connections Only Mode */ #define BTM_SEC_MODE4_LEVEL4 0x0040 /* Need to switch connection to be master */ #define BTM_SEC_FORCE_MASTER 0x0100 /* Try to switch connection to be master */ #define BTM_SEC_ATTEMPT_MASTER 0x0200 /* Need to switch connection to be master */ #define BTM_SEC_FORCE_SLAVE 0x0400 /* Try to switch connection to be slave */ #define BTM_SEC_ATTEMPT_SLAVE 0x0800 /* inbound Do man in the middle protection */ #define BTM_SEC_IN_MITM 0x1000 /* outbound Do man in the middle protection */ #define BTM_SEC_OUT_MITM 0x2000 /* enforce a minimum of 16 digit for sec mode 2 */ #define BTM_SEC_IN_MIN_16_DIGIT_PIN 0x4000 /* Security Flags [bit mask] (BTM_GetSecurityFlags) */ #define BTM_SEC_FLAG_AUTHORIZED 0x01 #define BTM_SEC_FLAG_AUTHENTICATED 0x02 #define BTM_SEC_FLAG_ENCRYPTED 0x04 #define BTM_SEC_FLAG_LKEY_KNOWN 0x10 #define BTM_SEC_FLAG_LKEY_AUTHED 0x20 /* PIN types */ #define BTM_PIN_TYPE_VARIABLE HCI_PIN_TYPE_VARIABLE #define BTM_PIN_TYPE_FIXED HCI_PIN_TYPE_FIXED /* Link Key types used to generate the new link key. * returned in link key notification callback function */ #define BTM_LKEY_TYPE_COMBINATION HCI_LKEY_TYPE_COMBINATION #define BTM_LKEY_TYPE_LOCAL_UNIT HCI_LKEY_TYPE_LOCAL_UNIT #define BTM_LKEY_TYPE_REMOTE_UNIT HCI_LKEY_TYPE_REMOTE_UNIT #define BTM_LKEY_TYPE_DEBUG_COMB HCI_LKEY_TYPE_DEBUG_COMB #define BTM_LKEY_TYPE_UNAUTH_COMB HCI_LKEY_TYPE_UNAUTH_COMB #define BTM_LKEY_TYPE_AUTH_COMB HCI_LKEY_TYPE_AUTH_COMB #define BTM_LKEY_TYPE_CHANGED_COMB HCI_LKEY_TYPE_CHANGED_COMB #define BTM_LKEY_TYPE_UNAUTH_COMB_P_256 HCI_LKEY_TYPE_UNAUTH_COMB_P_256 #define BTM_LKEY_TYPE_AUTH_COMB_P_256 HCI_LKEY_TYPE_AUTH_COMB_P_256 /* "easy" requirements for LK derived from LTK */ #define BTM_LTK_DERIVED_LKEY_OFFSET 0x20 #define BTM_LKEY_TYPE_IGNORE \ 0xff /* used when event is response from \ hci return link keys request */ typedef uint8_t tBTM_LINK_KEY_TYPE; /* Protocol level security (BTM_SetSecurityLevel) */ #define BTM_SEC_PROTO_L2CAP 0 #define BTM_SEC_PROTO_SDP 1 #define BTM_SEC_PROTO_TCS 2 #define BTM_SEC_PROTO_RFCOMM 3 #define BTM_SEC_PROTO_OBEX 4 #define BTM_SEC_PROTO_BNEP 5 #define BTM_SEC_PROTO_HID 6 /* HID */ #define BTM_SEC_PROTO_AVDT 7 #define BTM_SEC_PROTO_MCA 8 /* Determine the number of uint32_t's necessary for security services */ #define BTM_SEC_ARRAY_BITS 32 /* Number of bits in each array element */ #define BTM_SEC_SERVICE_ARRAY_SIZE \ (((uint32_t)BTM_SEC_MAX_SERVICES / BTM_SEC_ARRAY_BITS) + \ (((uint32_t)BTM_SEC_MAX_SERVICES % BTM_SEC_ARRAY_BITS) ? 1 : 0)) /* Security service definitions (BTM_SetSecurityLevel) * Used for Authorization APIs */ #define BTM_SEC_SERVICE_SDP_SERVER 0 #define BTM_SEC_SERVICE_SERIAL_PORT 1 #define BTM_SEC_SERVICE_LAN_ACCESS 2 #define BTM_SEC_SERVICE_DUN 3 #define BTM_SEC_SERVICE_IRMC_SYNC 4 #define BTM_SEC_SERVICE_IRMC_SYNC_CMD 5 #define BTM_SEC_SERVICE_OBEX 6 #define BTM_SEC_SERVICE_OBEX_FTP 7 #define BTM_SEC_SERVICE_HEADSET 8 #define BTM_SEC_SERVICE_CORDLESS 9 #define BTM_SEC_SERVICE_INTERCOM 10 #define BTM_SEC_SERVICE_FAX 11 #define BTM_SEC_SERVICE_HEADSET_AG 12 #define BTM_SEC_SERVICE_PNP_INFO 13 #define BTM_SEC_SERVICE_GEN_NET 14 #define BTM_SEC_SERVICE_GEN_FILE 15 #define BTM_SEC_SERVICE_GEN_AUDIO 16 #define BTM_SEC_SERVICE_GEN_TEL 17 #define BTM_SEC_SERVICE_CTP_DATA 18 #define BTM_SEC_SERVICE_HCRP_CTRL 19 #define BTM_SEC_SERVICE_HCRP_DATA 20 #define BTM_SEC_SERVICE_HCRP_NOTIF 21 #define BTM_SEC_SERVICE_BPP_JOB 22 #define BTM_SEC_SERVICE_BPP_STATUS 23 #define BTM_SEC_SERVICE_BPP_REF 24 #define BTM_SEC_SERVICE_BNEP_PANU 25 #define BTM_SEC_SERVICE_BNEP_GN 26 #define BTM_SEC_SERVICE_BNEP_NAP 27 #define BTM_SEC_SERVICE_HF_HANDSFREE 28 #define BTM_SEC_SERVICE_AG_HANDSFREE 29 #define BTM_SEC_SERVICE_TE_PHONE_ACCESS 30 #define BTM_SEC_SERVICE_ME_PHONE_ACCESS 31 #define BTM_SEC_SERVICE_HIDH_SEC_CTRL 32 #define BTM_SEC_SERVICE_HIDH_NOSEC_CTRL 33 #define BTM_SEC_SERVICE_HIDH_INTR 34 #define BTM_SEC_SERVICE_BIP 35 #define BTM_SEC_SERVICE_BIP_REF 36 #define BTM_SEC_SERVICE_AVDTP 37 #define BTM_SEC_SERVICE_AVDTP_NOSEC 38 #define BTM_SEC_SERVICE_AVCTP 39 #define BTM_SEC_SERVICE_SAP 40 #define BTM_SEC_SERVICE_PBAP 41 #define BTM_SEC_SERVICE_RFC_MUX 42 #define BTM_SEC_SERVICE_AVCTP_BROWSE 43 #define BTM_SEC_SERVICE_MAP 44 #define BTM_SEC_SERVICE_MAP_NOTIF 45 #define BTM_SEC_SERVICE_MCAP_CTRL 46 #define BTM_SEC_SERVICE_MCAP_DATA 47 #define BTM_SEC_SERVICE_HDP_SNK 48 #define BTM_SEC_SERVICE_HDP_SRC 49 #define BTM_SEC_SERVICE_ATT 50 #define BTM_SEC_SERVICE_HIDD_SEC_CTRL 51 #define BTM_SEC_SERVICE_HIDD_NOSEC_CTRL 52 #define BTM_SEC_SERVICE_HIDD_INTR 53 /* Update these as services are added */ #define BTM_SEC_SERVICE_FIRST_EMPTY 54 #ifndef BTM_SEC_MAX_SERVICES #define BTM_SEC_MAX_SERVICES 75 #endif /******************************************************************************* * Security Services MACROS handle array of uint32_t bits for more than 32 * trusted services ******************************************************************************/ /* MACRO to set the security service bit mask in a bit stream */ #define BTM_SEC_SET_SERVICE(p, service) \ (((uint32_t*)(p))[(((uint32_t)(service)) / BTM_SEC_ARRAY_BITS)] |= \ ((uint32_t)1 << (((uint32_t)(service)) % BTM_SEC_ARRAY_BITS))) /* MACRO to clear the security service bit mask in a bit stream */ #define BTM_SEC_CLR_SERVICE(p, service) \ (((uint32_t*)(p))[(((uint32_t)(service)) / BTM_SEC_ARRAY_BITS)] &= \ ~((uint32_t)1 << (((uint32_t)(service)) % BTM_SEC_ARRAY_BITS))) /* MACRO to check the security service bit mask in a bit stream (Returns true or * false) */ #define BTM_SEC_IS_SERVICE_TRUSTED(p, service) \ (((((uint32_t*)(p))[(((uint32_t)(service)) / BTM_SEC_ARRAY_BITS)]) & \ (uint32_t)(((uint32_t)1 << (((uint32_t)(service)) % BTM_SEC_ARRAY_BITS)))) \ ? true \ : false) /* MACRO to copy two trusted device bitmask */ #define BTM_SEC_COPY_TRUSTED_DEVICE(p_src, p_dst) \ { \ uint32_t trst; \ for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \ ((uint32_t*)(p_dst))[trst] = ((uint32_t*)(p_src))[trst]; \ } /* MACRO to clear two trusted device bitmask */ #define BTM_SEC_CLR_TRUSTED_DEVICE(p_dst) \ { \ uint32_t trst; \ for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \ ((uint32_t*)(p_dst))[trst] = 0; \ } /* Following bits can be provided by host in the trusted_mask array */ /* 0..31 bits of mask[0] (Least Significant Word) */ #define BTM_SEC_TRUST_SDP_SERVER (1 << BTM_SEC_SERVICE_SDP_SERVER) #define BTM_SEC_TRUST_SERIAL_PORT (1 << BTM_SEC_SERVICE_SERIAL_PORT) #define BTM_SEC_TRUST_LAN_ACCESS (1 << BTM_SEC_SERVICE_LAN_ACCESS) #define BTM_SEC_TRUST_DUN (1 << BTM_SEC_SERVICE_DUN) #define BTM_SEC_TRUST_IRMC_SYNC (1 << BTM_SEC_SERVICE_IRMC_SYNC) #define BTM_SEC_TRUST_IRMC_SYNC_CMD (1 << BTM_SEC_SERVICE_IRMC_SYNC_CMD) #define BTM_SEC_TRUST_OBEX (1 << BTM_SEC_SERVICE_OBEX) #define BTM_SEC_TRUST_OBEX_FTP (1 << BTM_SEC_SERVICE_OBEX_FTP) #define BTM_SEC_TRUST_HEADSET (1 << BTM_SEC_SERVICE_HEADSET) #define BTM_SEC_TRUST_CORDLESS (1 << BTM_SEC_SERVICE_CORDLESS) #define BTM_SEC_TRUST_INTERCOM (1 << BTM_SEC_SERVICE_INTERCOM) #define BTM_SEC_TRUST_FAX (1 << BTM_SEC_SERVICE_FAX) #define BTM_SEC_TRUST_HEADSET_AG (1 << BTM_SEC_SERVICE_HEADSET_AG) #define BTM_SEC_TRUST_PNP_INFO (1 << BTM_SEC_SERVICE_PNP_INFO) #define BTM_SEC_TRUST_GEN_NET (1 << BTM_SEC_SERVICE_GEN_NET) #define BTM_SEC_TRUST_GEN_FILE (1 << BTM_SEC_SERVICE_GEN_FILE) #define BTM_SEC_TRUST_GEN_AUDIO (1 << BTM_SEC_SERVICE_GEN_AUDIO) #define BTM_SEC_TRUST_GEN_TEL (1 << BTM_SEC_SERVICE_GEN_TEL) #define BTM_SEC_TRUST_CTP_DATA (1 << BTM_SEC_SERVICE_CTP_DATA) #define BTM_SEC_TRUST_HCRP_CTRL (1 << BTM_SEC_SERVICE_HCRP_CTRL) #define BTM_SEC_TRUST_HCRP_DATA (1 << BTM_SEC_SERVICE_HCRP_DATA) #define BTM_SEC_TRUST_HCRP_NOTIF (1 << BTM_SEC_SERVICE_HCRP_NOTIF) #define BTM_SEC_TRUST_BPP_JOB (1 << BTM_SEC_SERVICE_JOB) #define BTM_SEC_TRUST_BPP_STATUS (1 << BTM_SEC_SERVICE_STATUS) #define BTM_SEC_TRUST_BPP_REF (1 << BTM_SEC_SERVICE_REF) #define BTM_SEC_TRUST_BNEP_PANU (1 << BTM_SEC_SERVICE_BNEP_PANU) #define BTM_SEC_TRUST_BNEP_GN (1 << BTM_SEC_SERVICE_BNEP_GN) #define BTM_SEC_TRUST_BNEP_NAP (1 << BTM_SEC_SERVICE_BNEP_NAP) #define BTM_SEC_TRUST_HFP_HF (1 << BTM_SEC_SERVICE_HF_HANDSFREE) #define BTM_SEC_TRUST_HFP_AG (1 << BTM_SEC_SERVICE_AG_HANDSFREE) #define BTM_SEC_TRUST_TE_PHONE_ACCESS (1 << BTM_SEC_SERVICE_TE_PHONE_ACCESS) #define BTM_SEC_TRUST_ME_PHONE_ACCESS (1 << BTM_SEC_SERVICE_ME_PHONE_ACCESS) /* 0..31 bits of mask[1] (Most Significant Word) */ #define BTM_SEC_TRUST_HIDH_CTRL (1 << (BTM_SEC_SERVICE_HIDH_SEC_CTRL - 32)) #define BTM_SEC_TRUST_HIDH_NOSEC_CTRL \ (1 << (BTM_SEC_SERVICE_HIDH_NOSEC_CTRL - 32)) #define BTM_SEC_TRUST_HIDH_INTR (1 << (BTM_SEC_SERVICE_HIDH_INTR - 32)) #define BTM_SEC_TRUST_BIP (1 << (BTM_SEC_SERVICE_BIP - 32)) #define BTM_SEC_TRUST_BIP_REF (1 << (BTM_SEC_SERVICE_BIP_REF - 32)) #define BTM_SEC_TRUST_AVDTP (1 << (BTM_SEC_SERVICE_AVDTP - 32)) #define BTM_SEC_TRUST_AVDTP_NOSEC (1 << (BTM_SEC_SERVICE_AVDTP_NOSEC - 32)) #define BTM_SEC_TRUST_AVCTP (1 << (BTM_SEC_SERVICE_AVCTP - 32)) #define BTM_SEC_TRUST_SAP (1 << (BTM_SEC_SERVICE_SAP - 32)) #define BTM_SEC_TRUST_PBAP (1 << (BTM_SEC_SERVICE_PBAP - 32)) #define BTM_SEC_TRUST_RFC_MUX (1 << (BTM_SEC_SERVICE_RFC_MUX - 32)) #define BTM_SEC_TRUST_AVCTP_BROWSE (1 << (BTM_SEC_SERVICE_AVCTP_BROWSE - 32)) #define BTM_SEC_TRUST_MAP (1 << (BTM_SEC_SERVICE_MAP - 32)) #define BTM_SEC_TRUST_MAP_NOTIF (1 << (BTM_SEC_SERVICE_MAP_NOTIF - 32)) #define BTM_SEC_TRUST_MCAP_CTRL (1 << (BTM_SEC_SERVICE_MCAP_CTRL - 32)) #define BTM_SEC_TRUST_MCAP_DATA (1 << (BTM_SEC_SERVICE_MCAP_DATA - 32)) #define BTM_SEC_TRUST_HDP_SNK (1 << (BTM_SEC_SERVICE_HDP_SNK - 32)) #define BTM_SEC_TRUST_HDP_SRC (1 << (BTM_SEC_SERVICE_HDP_SRC - 32)) #define BTM_SEC_TRUST_ALL 0xFFFFFFFF /* for each array element */ /**************************************** * Security Manager Callback Functions ****************************************/ /* Authorize device for service. Parameters are * BD Address of remote * Device Class of remote * BD Name of remote * Service name * Service Id (NULL - unknown service or unused * [BTM_SEC_SERVICE_NAME_LEN set to 0]) * Is originator of the connection * Result of the operation */ typedef uint8_t(tBTM_AUTHORIZE_CALLBACK)(BD_ADDR bd_addr, DEV_CLASS dev_class, tBTM_BD_NAME bd_name, uint8_t* service_name, uint8_t service_id, bool is_originator); /* Get PIN for the connection. Parameters are * BD Address of remote * Device Class of remote * BD Name of remote * Flag indicating the minimum pin code length to be 16 digits */ typedef uint8_t(tBTM_PIN_CALLBACK)(BD_ADDR bd_addr, DEV_CLASS dev_class, tBTM_BD_NAME bd_name, bool min_16_digit); /* New Link Key for the connection. Parameters are * BD Address of remote * Link Key * Key Type: Combination, Local Unit, or Remote Unit */ typedef uint8_t(tBTM_LINK_KEY_CALLBACK)(BD_ADDR bd_addr, DEV_CLASS dev_class, tBTM_BD_NAME bd_name, uint8_t* key, uint8_t key_type); /* Remote Name Resolved. Parameters are * BD Address of remote * BD Name of remote */ typedef void(tBTM_RMT_NAME_CALLBACK)(BD_ADDR bd_addr, DEV_CLASS dc, tBTM_BD_NAME bd_name); /* Authentication complete for the connection. Parameters are * BD Address of remote * Device Class of remote * BD Name of remote * */ typedef uint8_t(tBTM_AUTH_COMPLETE_CALLBACK)(BD_ADDR bd_addr, DEV_CLASS dev_class, tBTM_BD_NAME bd_name, int result); enum { BTM_SP_IO_REQ_EVT, /* received IO_CAPABILITY_REQUEST event */ BTM_SP_IO_RSP_EVT, /* received IO_CAPABILITY_RESPONSE event */ BTM_SP_CFM_REQ_EVT, /* received USER_CONFIRMATION_REQUEST event */ BTM_SP_KEY_NOTIF_EVT, /* received USER_PASSKEY_NOTIFY event */ BTM_SP_KEY_REQ_EVT, /* received USER_PASSKEY_REQUEST event */ BTM_SP_KEYPRESS_EVT, /* received KEYPRESS_NOTIFY event */ BTM_SP_LOC_OOB_EVT, /* received result for READ_LOCAL_OOB_DATA command */ BTM_SP_RMT_OOB_EVT, /* received REMOTE_OOB_DATA_REQUEST event */ BTM_SP_COMPLT_EVT, /* received SIMPLE_PAIRING_COMPLETE event */ BTM_SP_UPGRADE_EVT /* check if the application wants to upgrade the link key */ }; typedef uint8_t tBTM_SP_EVT; #define BTM_IO_CAP_OUT 0 /* DisplayOnly */ #define BTM_IO_CAP_IO 1 /* DisplayYesNo */ #define BTM_IO_CAP_IN 2 /* KeyboardOnly */ #define BTM_IO_CAP_NONE 3 /* NoInputNoOutput */ #define BTM_IO_CAP_KBDISP 4 /* Keyboard display */ #define BTM_IO_CAP_MAX 5 #define BTM_IO_CAP_UNKNOWN 0xFF /* Unknown value */ typedef uint8_t tBTM_IO_CAP; #define BTM_MAX_PASSKEY_VAL (999999) #define BTM_MIN_PASSKEY_VAL (0) /* MITM Protection Not Required - Single Profile/non-bonding Numeric comparison * with automatic accept allowed */ #define BTM_AUTH_SP_NO 0 /* MITM Protection Required - Single Profile/non-bonding. Use IO Capabilities to * determine authentication procedure */ #define BTM_AUTH_SP_YES 1 /* MITM Protection Not Required - All Profiles/dedicated bonding Numeric * comparison with automatic accept allowed */ #define BTM_AUTH_AP_NO 2 /* MITM Protection Required - All Profiles/dedicated bonding Use IO Capabilities * to determine authentication procedure */ #define BTM_AUTH_AP_YES 3 /* MITM Protection Not Required - Single Profiles/general bonding Numeric * comparison with automatic accept allowed */ #define BTM_AUTH_SPGB_NO 4 /* MITM Protection Required - Single Profiles/general bonding Use IO * Capabilities to determine authentication procedure */ #define BTM_AUTH_SPGB_YES 5 /* this bit is ORed with BTM_AUTH_SP_* when IO exchange for dedicated bonding */ #define BTM_AUTH_DD_BOND 2 #define BTM_AUTH_GB_BIT 4 /* the genernal bonding bit */ #define BTM_AUTH_BONDS 6 /* the general/dedicated bonding bits */ #define BTM_AUTH_YN_BIT 1 /* this is the Yes or No bit */ #define BTM_BLE_INITIATOR_KEY_SIZE 15 #define BTM_BLE_RESPONDER_KEY_SIZE 15 #define BTM_BLE_MAX_KEY_SIZE 16 typedef uint8_t tBTM_AUTH_REQ; enum { BTM_OOB_NONE, BTM_OOB_PRESENT, BTM_OOB_UNKNOWN }; typedef uint8_t tBTM_OOB_DATA; /* data type for BTM_SP_IO_REQ_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ tBTM_IO_CAP io_cap; /* local IO capabilities */ tBTM_OOB_DATA oob_data; /* OOB data present (locally) for the peer device */ tBTM_AUTH_REQ auth_req; /* Authentication required (for local device) */ bool is_orig; /* true, if local device initiated the SP process */ } tBTM_SP_IO_REQ; /* data type for BTM_SP_IO_RSP_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ tBTM_IO_CAP io_cap; /* peer IO capabilities */ tBTM_OOB_DATA oob_data; /* OOB data present at peer device for the local device */ tBTM_AUTH_REQ auth_req; /* Authentication required for peer device */ } tBTM_SP_IO_RSP; /* data type for BTM_SP_CFM_REQ_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ tBTM_BD_NAME bd_name; /* peer device name */ uint32_t num_val; /* the numeric value for comparison. If just_works, do not show this number to UI */ bool just_works; /* true, if "Just Works" association model */ tBTM_AUTH_REQ loc_auth_req; /* Authentication required for local device */ tBTM_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */ tBTM_IO_CAP loc_io_caps; /* IO Capabilities of the local device */ tBTM_IO_CAP rmt_io_caps; /* IO Capabilities of the remot device */ } tBTM_SP_CFM_REQ; /* data type for BTM_SP_KEY_REQ_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ tBTM_BD_NAME bd_name; /* peer device name */ } tBTM_SP_KEY_REQ; /* data type for BTM_SP_KEY_NOTIF_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ tBTM_BD_NAME bd_name; /* peer device name */ uint32_t passkey; /* passkey */ } tBTM_SP_KEY_NOTIF; enum { BTM_SP_KEY_STARTED, /* 0 - passkey entry started */ BTM_SP_KEY_ENTERED, /* 1 - passkey digit entered */ BTM_SP_KEY_ERASED, /* 2 - passkey digit erased */ BTM_SP_KEY_CLEARED, /* 3 - passkey cleared */ BTM_SP_KEY_COMPLT, /* 4 - passkey entry completed */ BTM_SP_KEY_OUT_OF_RANGE /* 5 - out of range */ }; typedef uint8_t tBTM_SP_KEY_TYPE; /* data type for BTM_SP_KEYPRESS_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ tBTM_SP_KEY_TYPE notif_type; } tBTM_SP_KEYPRESS; /* data type for BTM_SP_LOC_OOB_EVT */ typedef struct { tBTM_STATUS status; /* */ BT_OCTET16 c; /* Simple Pairing Hash C */ BT_OCTET16 r; /* Simple Pairing Randomnizer R */ } tBTM_SP_LOC_OOB; /* data type for BTM_SP_RMT_OOB_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ tBTM_BD_NAME bd_name; /* peer device name */ } tBTM_SP_RMT_OOB; /* data type for BTM_SP_COMPLT_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ DEV_CLASS dev_class; /* peer CoD */ tBTM_BD_NAME bd_name; /* peer device name */ tBTM_STATUS status; /* status of the simple pairing process */ } tBTM_SP_COMPLT; /* data type for BTM_SP_UPGRADE_EVT */ typedef struct { BD_ADDR bd_addr; /* peer address */ bool upgrade; /* true, to upgrade the link key */ } tBTM_SP_UPGRADE; typedef union { tBTM_SP_IO_REQ io_req; /* BTM_SP_IO_REQ_EVT */ tBTM_SP_IO_RSP io_rsp; /* BTM_SP_IO_RSP_EVT */ tBTM_SP_CFM_REQ cfm_req; /* BTM_SP_CFM_REQ_EVT */ tBTM_SP_KEY_NOTIF key_notif; /* BTM_SP_KEY_NOTIF_EVT */ tBTM_SP_KEY_REQ key_req; /* BTM_SP_KEY_REQ_EVT */ tBTM_SP_KEYPRESS key_press; /* BTM_SP_KEYPRESS_EVT */ tBTM_SP_LOC_OOB loc_oob; /* BTM_SP_LOC_OOB_EVT */ tBTM_SP_RMT_OOB rmt_oob; /* BTM_SP_RMT_OOB_EVT */ tBTM_SP_COMPLT complt; /* BTM_SP_COMPLT_EVT */ tBTM_SP_UPGRADE upgrade; /* BTM_SP_UPGRADE_EVT */ } tBTM_SP_EVT_DATA; /* Simple Pairing Events. Called by the stack when Simple Pairing related * events occur. */ typedef uint8_t(tBTM_SP_CALLBACK)(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); typedef void(tBTM_MKEY_CALLBACK)(BD_ADDR bd_addr, uint8_t status, uint8_t key_flag); /* Encryption enabled/disabled complete: Optionally passed with * BTM_SetEncryption. * Parameters are * BD Address of remote * optional data passed in by BTM_SetEncryption * tBTM_STATUS - result of the operation */ typedef void(tBTM_SEC_CBACK)(BD_ADDR bd_addr, tBT_TRANSPORT trasnport, void* p_ref_data, tBTM_STATUS result); /* Bond Cancel complete. Parameters are * Result of the cancel operation * */ typedef void(tBTM_BOND_CANCEL_CMPL_CALLBACK)(tBTM_STATUS result); /* LE related event and data structure */ /* received IO_CAPABILITY_REQUEST event */ #define BTM_LE_IO_REQ_EVT SMP_IO_CAP_REQ_EVT /* security request event */ #define BTM_LE_SEC_REQUEST_EVT SMP_SEC_REQUEST_EVT /* received USER_PASSKEY_NOTIFY event */ #define BTM_LE_KEY_NOTIF_EVT SMP_PASSKEY_NOTIF_EVT /* received USER_PASSKEY_REQUEST event */ #define BTM_LE_KEY_REQ_EVT SMP_PASSKEY_REQ_EVT /* OOB data request event */ #define BTM_LE_OOB_REQ_EVT SMP_OOB_REQ_EVT /* Numeric Comparison request event */ #define BTM_LE_NC_REQ_EVT SMP_NC_REQ_EVT /* Peer keypress notification recd event */ #define BTM_LE_PR_KEYPR_NOT_EVT SMP_PEER_KEYPR_NOT_EVT /* SC OOB request event (both local and peer OOB data) can be expected in * response */ #define BTM_LE_SC_OOB_REQ_EVT SMP_SC_OOB_REQ_EVT /* SC OOB local data set is created (as result of SMP_CrLocScOobData(...)) */ #define BTM_LE_SC_LOC_OOB_EVT SMP_SC_LOC_OOB_DATA_UP_EVT /* SMP over BR keys request event */ #define BTM_LE_BR_KEYS_REQ_EVT SMP_BR_KEYS_REQ_EVT /* SMP complete event */ #define BTM_LE_COMPLT_EVT SMP_COMPLT_EVT #define BTM_LE_LAST_FROM_SMP BTM_LE_BR_KEYS_REQ_EVT /* KEY update event */ #define BTM_LE_KEY_EVT (BTM_LE_LAST_FROM_SMP + 1) typedef uint8_t tBTM_LE_EVT; #define BTM_LE_KEY_NONE 0 /* encryption information of peer device */ #define BTM_LE_KEY_PENC SMP_SEC_KEY_TYPE_ENC /* identity key of the peer device */ #define BTM_LE_KEY_PID SMP_SEC_KEY_TYPE_ID /* peer SRK */ #define BTM_LE_KEY_PCSRK SMP_SEC_KEY_TYPE_CSRK #define BTM_LE_KEY_PLK SMP_SEC_KEY_TYPE_LK #define BTM_LE_KEY_LLK (SMP_SEC_KEY_TYPE_LK << 4) /* master role security information:div */ #define BTM_LE_KEY_LENC (SMP_SEC_KEY_TYPE_ENC << 4) /* master device ID key */ #define BTM_LE_KEY_LID (SMP_SEC_KEY_TYPE_ID << 4) /* local CSRK has been deliver to peer */ #define BTM_LE_KEY_LCSRK (SMP_SEC_KEY_TYPE_CSRK << 4) typedef uint8_t tBTM_LE_KEY_TYPE; #define BTM_LE_AUTH_REQ_NO_BOND SMP_AUTH_NO_BOND /* 0 */ #define BTM_LE_AUTH_REQ_BOND SMP_AUTH_GEN_BOND /* 1 << 0 */ #define BTM_LE_AUTH_REQ_MITM SMP_AUTH_YN_BIT /* 1 << 2 */ typedef uint8_t tBTM_LE_AUTH_REQ; #define BTM_LE_SC_SUPPORT_BIT SMP_SC_SUPPORT_BIT /* (1 << 3) */ #define BTM_LE_KP_SUPPORT_BIT SMP_KP_SUPPORT_BIT /* (1 << 4) */ #define BTM_LE_H7_SUPPORT_BIT SMP_H7_SUPPORT_BIT /* (1 << 5) */ #define BTM_LE_AUTH_REQ_SC_ONLY SMP_AUTH_SC_ENC_ONLY /* 00101000 */ #define BTM_LE_AUTH_REQ_SC_BOND SMP_AUTH_SC_GB /* 00101001 */ #define BTM_LE_AUTH_REQ_SC_MITM SMP_AUTH_SC_MITM_NB /* 00101100 */ #define BTM_LE_AUTH_REQ_SC_MITM_BOND SMP_AUTH_SC_MITM_GB /* 00101101 */ #define BTM_LE_AUTH_REQ_MASK SMP_AUTH_MASK /* 0x3D */ /* LE security level */ #define BTM_LE_SEC_NONE SMP_SEC_NONE #define BTM_LE_SEC_UNAUTHENTICATE SMP_SEC_UNAUTHENTICATE /* 1 */ #define BTM_LE_SEC_AUTHENTICATED SMP_SEC_AUTHENTICATED /* 4 */ typedef uint8_t tBTM_LE_SEC; typedef struct { /* local IO capabilities */ tBTM_IO_CAP io_cap; /* OOB data present (locally) for the peer device */ uint8_t oob_data; /* Authentication request (for local device) containing bonding and MITM * info */ tBTM_LE_AUTH_REQ auth_req; uint8_t max_key_size; /* max encryption key size */ tBTM_LE_KEY_TYPE init_keys; /* keys to be distributed, bit mask */ tBTM_LE_KEY_TYPE resp_keys; /* keys to be distributed, bit mask */ } tBTM_LE_IO_REQ; /* data type for tBTM_LE_COMPLT */ typedef struct { uint8_t reason; uint8_t sec_level; bool is_pair_cancel; bool smp_over_br; } tBTM_LE_COMPLT; /* BLE encryption keys */ typedef struct { BT_OCTET16 ltk; BT_OCTET8 rand; uint16_t ediv; uint8_t sec_level; uint8_t key_size; } tBTM_LE_PENC_KEYS; /* BLE CSRK keys */ typedef struct { uint32_t counter; BT_OCTET16 csrk; uint8_t sec_level; } tBTM_LE_PCSRK_KEYS; /* BLE Encryption reproduction keys */ typedef struct { BT_OCTET16 ltk; uint16_t div; uint8_t key_size; uint8_t sec_level; } tBTM_LE_LENC_KEYS; /* BLE SRK keys */ typedef struct { uint32_t counter; uint16_t div; uint8_t sec_level; BT_OCTET16 csrk; } tBTM_LE_LCSRK_KEYS; typedef struct { BT_OCTET16 irk; tBLE_ADDR_TYPE addr_type; BD_ADDR static_addr; } tBTM_LE_PID_KEYS; typedef union { tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */ tBTM_LE_PCSRK_KEYS pcsrk_key; /* received peer device SRK */ tBTM_LE_PID_KEYS pid_key; /* peer device ID key */ tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys * LTK = = d1(ER,DIV,0) */ tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/ } tBTM_LE_KEY_VALUE; typedef struct { tBTM_LE_KEY_TYPE key_type; tBTM_LE_KEY_VALUE* p_key_value; } tBTM_LE_KEY; typedef union { tBTM_LE_IO_REQ io_req; /* BTM_LE_IO_REQ_EVT */ uint32_t key_notif; /* BTM_LE_KEY_NOTIF_EVT */ /* BTM_LE_NC_REQ_EVT */ /* no callback data for * BTM_LE_KEY_REQ_EVT * and BTM_LE_OOB_REQ_EVT */ tBTM_LE_COMPLT complt; /* BTM_LE_COMPLT_EVT */ tSMP_OOB_DATA_TYPE req_oob_type; tBTM_LE_KEY key; } tBTM_LE_EVT_DATA; /* Simple Pairing Events. Called by the stack when Simple Pairing related * events occur. */ typedef uint8_t(tBTM_LE_CALLBACK)(tBTM_LE_EVT event, BD_ADDR bda, tBTM_LE_EVT_DATA* p_data); #define BTM_BLE_KEY_TYPE_ID 1 #define BTM_BLE_KEY_TYPE_ER 2 #define BTM_BLE_KEY_TYPE_COUNTER 3 // tobe obsolete typedef struct { BT_OCTET16 ir; BT_OCTET16 irk; BT_OCTET16 dhk; } tBTM_BLE_LOCAL_ID_KEYS; typedef union { tBTM_BLE_LOCAL_ID_KEYS id_keys; BT_OCTET16 er; } tBTM_BLE_LOCAL_KEYS; /* New LE identity key for local device. */ typedef void(tBTM_LE_KEY_CALLBACK)(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key); /*************************** * Security Manager Types ***************************/ /* Structure that applications use to register with BTM_SecRegister */ typedef struct { tBTM_AUTHORIZE_CALLBACK* p_authorize_callback; tBTM_PIN_CALLBACK* p_pin_callback; tBTM_LINK_KEY_CALLBACK* p_link_key_callback; tBTM_AUTH_COMPLETE_CALLBACK* p_auth_complete_callback; tBTM_BOND_CANCEL_CMPL_CALLBACK* p_bond_cancel_cmpl_callback; tBTM_SP_CALLBACK* p_sp_callback; tBTM_LE_CALLBACK* p_le_callback; tBTM_LE_KEY_CALLBACK* p_le_key_callback; } tBTM_APPL_INFO; /* Callback function for when a link supervision timeout event occurs. * This asynchronous event is enabled/disabled by calling BTM_RegForLstoEvt(). */ typedef void(tBTM_LSTO_CBACK)(BD_ADDR remote_bda, uint16_t timeout); /***************************************************************************** * POWER MANAGEMENT ****************************************************************************/ /**************************** * Power Manager Constants ****************************/ /* BTM Power manager status codes */ enum { BTM_PM_STS_ACTIVE = HCI_MODE_ACTIVE, BTM_PM_STS_HOLD = HCI_MODE_HOLD, BTM_PM_STS_SNIFF = HCI_MODE_SNIFF, BTM_PM_STS_PARK = HCI_MODE_PARK, BTM_PM_STS_SSR, /* report the SSR parameters in HCI_SNIFF_SUB_RATE_EVT */ BTM_PM_STS_PENDING, /* when waiting for status from controller */ BTM_PM_STS_ERROR /* when HCI command status returns error */ }; typedef uint8_t tBTM_PM_STATUS; /* BTM Power manager modes */ enum { BTM_PM_MD_ACTIVE = BTM_PM_STS_ACTIVE, BTM_PM_MD_HOLD = BTM_PM_STS_HOLD, BTM_PM_MD_SNIFF = BTM_PM_STS_SNIFF, BTM_PM_MD_PARK = BTM_PM_STS_PARK, BTM_PM_MD_FORCE = 0x10 /* OR this to force ACL link to a certain mode */ }; typedef uint8_t tBTM_PM_MODE; #define BTM_PM_SET_ONLY_ID 0x80 /* Operation codes */ /* The module wants to set the desired power mode */ #define BTM_PM_REG_SET 1 /* The module wants to receive mode change event */ #define BTM_PM_REG_NOTIF 2 /* The module does not want to involve with PM anymore */ #define BTM_PM_DEREG 4 /************************ * Power Manager Types ************************/ typedef struct { uint16_t max; uint16_t min; uint16_t attempt; uint16_t timeout; tBTM_PM_MODE mode; } tBTM_PM_PWR_MD; /************************************* * Power Manager Callback Functions *************************************/ typedef void(tBTM_PM_STATUS_CBACK)(BD_ADDR p_bda, tBTM_PM_STATUS status, uint16_t value, uint8_t hci_status); /************************ * Stored Linkkey Types ************************/ #define BTM_CB_EVT_DELETE_STORED_LINK_KEYS 4 typedef struct { uint8_t event; uint8_t status; uint16_t num_keys; } tBTM_DELETE_STORED_LINK_KEY_COMPLETE; /* MIP evnets, callbacks */ enum { BTM_MIP_MODE_CHG_EVT, BTM_MIP_DISCONNECT_EVT, BTM_MIP_PKTS_COMPL_EVT, BTM_MIP_RXDATA_EVT }; typedef uint8_t tBTM_MIP_EVT; typedef struct { tBTM_MIP_EVT event; BD_ADDR bd_addr; uint16_t mip_id; } tBTM_MIP_MODE_CHANGE; typedef struct { tBTM_MIP_EVT event; uint16_t mip_id; uint8_t disc_reason; } tBTM_MIP_CONN_TIMEOUT; #define BTM_MIP_MAX_RX_LEN 17 typedef struct { tBTM_MIP_EVT event; uint16_t mip_id; uint8_t rx_len; uint8_t rx_data[BTM_MIP_MAX_RX_LEN]; } tBTM_MIP_RXDATA; typedef struct { tBTM_MIP_EVT event; BD_ADDR bd_addr; uint8_t data[11]; /* data[0] shows Vender-specific device type */ } tBTM_MIP_EIR_HANDSHAKE; typedef struct { tBTM_MIP_EVT event; uint16_t num_sent; /* Completed packet count at the controller */ } tBTM_MIP_PKTS_COMPL; typedef union { tBTM_MIP_EVT event; tBTM_MIP_MODE_CHANGE mod_chg; tBTM_MIP_CONN_TIMEOUT conn_tmo; tBTM_MIP_EIR_HANDSHAKE eir; tBTM_MIP_PKTS_COMPL completed; tBTM_MIP_RXDATA rxdata; } tBTM_MIP_EVENT_DATA; /* MIP event callback function */ typedef void(tBTM_MIP_EVENTS_CB)(tBTM_MIP_EVT event, tBTM_MIP_EVENT_DATA data); /* MIP Device query callback function */ typedef bool(tBTM_MIP_QUERY_CB)(BD_ADDR dev_addr, uint8_t* p_mode, LINK_KEY link_key); /* ACL link on, SCO link ongoing, sniff mode */ #define BTM_CONTRL_ACTIVE 1 /* Scan state - paging/inquiry/trying to connect*/ #define BTM_CONTRL_SCAN 2 /* Idle state - page scan, LE advt, inquiry scan */ #define BTM_CONTRL_IDLE 3 typedef uint8_t tBTM_CONTRL_STATE; #endif // BTM_API_TYPES_H
37.345289
80
0.720073
[ "model" ]
e4a6f0d3ed08f1079010c9c950a6ce59313edae6
74,816
c
C
dovecot-2.2.33.2/src/lib-http/test-http-client-errors.c
NicoleRobin/dovecot
f971413537673e781c00808bc039fde5749fcc95
[ "MIT" ]
null
null
null
dovecot-2.2.33.2/src/lib-http/test-http-client-errors.c
NicoleRobin/dovecot
f971413537673e781c00808bc039fde5749fcc95
[ "MIT" ]
null
null
null
dovecot-2.2.33.2/src/lib-http/test-http-client-errors.c
NicoleRobin/dovecot
f971413537673e781c00808bc039fde5749fcc95
[ "MIT" ]
null
null
null
/* Copyright (c) 2016-2017 Dovecot authors, see the included COPYING file */ #include "lib.h" #include "str.h" #include "hostpid.h" #include "ioloop.h" #include "istream.h" #include "istream-chain.h" #include "ostream.h" #include "time-util.h" #include "connection.h" #include "test-common.h" #include "http-url.h" #include "http-request.h" #include "http-client.h" #include <sys/types.h> #include <sys/wait.h> #include <signal.h> #include <unistd.h> /* * Types */ struct server_connection { struct connection conn; pool_t pool; }; typedef void (*test_server_init_t)(unsigned int index); typedef bool (*test_client_init_t) (const struct http_client_settings *client_set); typedef void (*test_dns_init_t)(void); /* * State */ /* common */ static struct ip_addr bind_ip; static in_port_t *bind_ports = 0; static struct ioloop *ioloop; static bool debug = FALSE; /* dns */ static pid_t dns_pid = (pid_t)-1; /* server */ static struct io *io_listen; static int fd_listen = -1; static pid_t *server_pids = NULL; static unsigned int server_pids_count = 0; static struct connection_list *server_conn_list; static size_t server_read_max = 0; static unsigned int server_index; static void (*test_server_input)(struct server_connection *conn); /* client */ static struct http_client *http_client = NULL; /* * Forward declarations */ /* server */ static void test_server_run(unsigned int index); static void server_connection_deinit(struct server_connection **_conn); /* client */ static void test_client_defaults(struct http_client_settings *http_set); static void test_client_deinit(void); /* test*/ static void test_run_client_server( const struct http_client_settings *client_set, test_client_init_t client_test, test_server_init_t server_test, unsigned int server_tests_count, test_dns_init_t dns_test) ATTR_NULL(3); /* * Unconfigured SSL */ /* client */ struct _unconfigured_ssl { unsigned int count; }; static void test_client_unconfigured_ssl_response( const struct http_response *resp, struct _unconfigured_ssl *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_unconfigured_ssl(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _unconfigured_ssl *ctx; ctx = i_new(struct _unconfigured_ssl, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "127.0.0.1", "/unconfigured-ssl.txt", test_client_unconfigured_ssl_response, ctx); http_client_request_set_ssl(hreq, TRUE); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "127.0.0.1", "/unconfigured-ssl2.txt", test_client_unconfigured_ssl_response, ctx); http_client_request_set_ssl(hreq, TRUE); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_unconfigured_ssl(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("unconfigured ssl"); test_run_client_server(&http_client_set, test_client_unconfigured_ssl, NULL, 0, NULL); test_end(); } /* * Unconfigured SSL abort */ /* client */ struct _unconfigured_ssl_abort { unsigned int count; }; static void test_client_unconfigured_ssl_abort_response1( const struct http_response *resp, struct _unconfigured_ssl_abort *ctx ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_out_quiet("inappropriate callback", FALSE); } static void test_client_unconfigured_ssl_abort_response2( const struct http_response *resp, struct _unconfigured_ssl_abort *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); i_free(ctx); io_loop_stop(ioloop); } static bool test_client_unconfigured_ssl_abort(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _unconfigured_ssl_abort *ctx; ctx = i_new(struct _unconfigured_ssl_abort, 1); ctx->count = 1; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "127.0.0.1", "/unconfigured-ssl.txt", test_client_unconfigured_ssl_abort_response1, ctx); http_client_request_set_ssl(hreq, TRUE); http_client_request_submit(hreq); http_client_request_abort(&hreq); hreq = http_client_request(http_client, "GET", "127.0.0.1", "/unconfigured-ssl2.txt", test_client_unconfigured_ssl_abort_response2, ctx); http_client_request_set_ssl(hreq, TRUE); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_unconfigured_ssl_abort(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("unconfigured ssl abort"); test_run_client_server(&http_client_set, test_client_unconfigured_ssl_abort, NULL, 0, NULL); test_end(); } /* * Invalid URL */ /* client */ struct _invalid_url { unsigned int count; }; static void test_client_invalid_url_response( const struct http_response *resp, struct _invalid_url *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_INVALID_URL); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_invalid_url(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _invalid_url *ctx; ctx = i_new(struct _invalid_url, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request_url_str(http_client, "GET", "imap://example.com/INBOX", test_client_invalid_url_response, ctx); http_client_request_submit(hreq); hreq = http_client_request_url_str(http_client, "GET", "http:/www.example.com", test_client_invalid_url_response, ctx); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_invalid_url(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("invalid url"); test_run_client_server(&http_client_set, test_client_invalid_url, NULL, 0, NULL); test_end(); } /* * Host lookup failed */ /* client */ struct _host_lookup_failed { unsigned int count; }; static void test_client_host_lookup_failed_response( const struct http_response *resp, struct _host_lookup_failed *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_host_lookup_failed(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _host_lookup_failed *ctx; ctx = i_new(struct _host_lookup_failed, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "host.in-addr.arpa", "/host-lookup-failed.txt", test_client_host_lookup_failed_response, ctx); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "host.in-addr.arpa", "/host-lookup-failed2.txt", test_client_host_lookup_failed_response, ctx); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_host_lookup_failed(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("host lookup failed"); test_run_client_server(&http_client_set, test_client_host_lookup_failed, NULL, 0, NULL); test_end(); } /* * Connection refused */ /* server */ static void test_server_connection_refused(unsigned int index ATTR_UNUSED) { i_close_fd(&fd_listen); } /* client */ struct _connection_refused { unsigned int count; struct timeout *to; }; static void test_client_connection_refused_response( const struct http_response *resp, struct _connection_refused *ctx) { test_assert(ctx->to == NULL); if (ctx->to != NULL) timeout_remove(&ctx->to); if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static void test_client_connection_refused_timeout(struct _connection_refused *ctx) { if (debug) i_debug("TIMEOUT (ok)"); timeout_remove(&ctx->to); } static bool test_client_connection_refused(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _connection_refused *ctx; ctx = i_new(struct _connection_refused, 1); ctx->count = 2; if (client_set->max_connect_attempts > 0) { ctx->to = timeout_add_short(250, test_client_connection_refused_timeout, ctx); } http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-refused.txt", test_client_connection_refused_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-refused2.txt", test_client_connection_refused_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_connection_refused(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("connection refused"); test_run_client_server(&http_client_set, test_client_connection_refused, test_server_connection_refused, 1, NULL); test_end(); http_client_set.max_connect_attempts = 3; test_begin("connection refused backoff"); test_run_client_server(&http_client_set, test_client_connection_refused, test_server_connection_refused, 1, NULL); test_end(); } /* * Connection lost prematurely */ /* server */ static void test_server_connection_lost_prematurely_input(struct server_connection *conn) { server_connection_deinit(&conn); } static void test_server_connection_lost_prematurely(unsigned int index) { test_server_input = test_server_connection_lost_prematurely_input; test_server_run(index); } /* client */ struct _connection_lost_prematurely { unsigned int count; struct timeout *to; }; static void test_client_connection_lost_prematurely_response( const struct http_response *resp, struct _connection_lost_prematurely *ctx) { test_assert(ctx->to == NULL); if (ctx->to != NULL) timeout_remove(&ctx->to); if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECTION_LOST); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static void test_client_connection_lost_prematurely_timeout( struct _connection_lost_prematurely *ctx) { if (debug) i_debug("TIMEOUT (ok)"); timeout_remove(&ctx->to); } static bool test_client_connection_lost_prematurely(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _connection_lost_prematurely *ctx; ctx = i_new(struct _connection_lost_prematurely, 1); ctx->count = 2; ctx->to = timeout_add_short(250, test_client_connection_lost_prematurely_timeout, ctx); http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-refused-retry.txt", test_client_connection_lost_prematurely_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-refused-retry2.txt", test_client_connection_lost_prematurely_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_connection_lost_prematurely(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.max_connect_attempts = 3; http_client_set.max_attempts = 3; test_begin("connection lost prematurely"); test_run_client_server(&http_client_set, test_client_connection_lost_prematurely, test_server_connection_lost_prematurely, 1, NULL); test_end(); } /* * Connection timed out */ /* client */ struct _connection_timed_out { unsigned int count; }; static void test_client_connection_timed_out_response( const struct http_response *resp, struct _connection_timed_out *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_connection_timed_out( const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _connection_timed_out *ctx; ctx = i_new(struct _connection_timed_out, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "192.168.0.0", "/connection-timed-out.txt", test_client_connection_timed_out_response, ctx); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "192.168.0.0", "/connection-timed-out2.txt", test_client_connection_timed_out_response, ctx); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_connection_timed_out(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.connect_timeout_msecs = 1000; http_client_set.max_attempts = 1; test_begin("connection timed out"); test_run_client_server(&http_client_set, test_client_connection_timed_out, NULL, 0, NULL); test_end(); } /* * Invalid redirect */ /* server */ /* -> not accepted */ static void test_invalid_redirect_input1(struct server_connection *conn) { static const char *resp = "HTTP/1.1 302 Redirect\r\n" "Location: http://localhost:4444\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_invalid_redirect1(unsigned int index) { test_server_input = test_invalid_redirect_input1; test_server_run(index); } /* -> bad location */ static void test_invalid_redirect_input2(struct server_connection *conn) { static const char *resp = "HTTP/1.1 302 Redirect\r\n" "Location: unix:/var/run/dovecot/auth-master\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_invalid_redirect2(unsigned int index) { test_server_input = test_invalid_redirect_input2; test_server_run(index); } /* -> too many */ static void test_invalid_redirect_input3(struct server_connection *conn) { string_t *resp; resp = t_str_new(512); str_printfa(resp, "HTTP/1.1 302 Redirect\r\n" "Location: http://%s:%u/friep.txt\r\n" "\r\n", net_ip2addr(&bind_ip), bind_ports[server_index+1]); o_stream_nsend(conn->conn.output, str_data(resp), str_len(resp)); server_connection_deinit(&conn); } static void test_server_invalid_redirect3(unsigned int index) { test_server_input = test_invalid_redirect_input3; test_server_run(index); } /* client */ static void test_client_invalid_redirect_response( const struct http_response *resp, void *context ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_INVALID_REDIRECT); test_assert(resp->reason != NULL && *resp->reason != '\0'); io_loop_stop(ioloop); } static bool test_client_invalid_redirect(const struct http_client_settings *client_set) { struct http_client_request *hreq; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/invalid-redirect.txt", test_client_invalid_redirect_response, NULL); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_invalid_redirect(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("invalid redirect: not accepted"); http_client_set.max_redirects = 0; test_run_client_server(&http_client_set, test_client_invalid_redirect, test_server_invalid_redirect1, 1, NULL); test_end(); test_begin("invalid redirect: bad location"); http_client_set.max_redirects = 1; test_run_client_server(&http_client_set, test_client_invalid_redirect, test_server_invalid_redirect2, 1, NULL); test_end(); test_begin("invalid redirect: too many"); http_client_set.max_redirects = 1; test_run_client_server(&http_client_set, test_client_invalid_redirect, test_server_invalid_redirect3, 3, NULL); test_end(); } /* * Unseekable redirect */ /* server */ static void test_unseekable_redirect_input(struct server_connection *conn) { string_t *resp; resp = t_str_new(512); str_printfa(resp, "HTTP/1.1 302 Redirect\r\n" "Location: http://%s:%u/frml.txt\r\n" "\r\n", net_ip2addr(&bind_ip), bind_ports[server_index+1]); o_stream_nsend(conn->conn.output, str_data(resp), str_len(resp)); server_connection_deinit(&conn); } static void test_server_unseekable_redirect(unsigned int index) { test_server_input = test_unseekable_redirect_input; test_server_run(index); } /* client */ static void test_client_unseekable_redirect_response( const struct http_response *resp, void *context ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_ABORTED); test_assert(resp->reason != NULL && *resp->reason != '\0'); io_loop_stop(ioloop); } static bool test_client_unseekable_redirect(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct istream *input; http_client = http_client_init(client_set); input = i_stream_create_from_data("FROP", 4); input->seekable = FALSE; hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/unseekable-redirect.txt", test_client_unseekable_redirect_response, NULL); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, FALSE); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_unseekable_redirect(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.max_redirects = 1; test_begin("unseekable redirect"); test_run_client_server(&http_client_set, test_client_unseekable_redirect, test_server_unseekable_redirect, 2, NULL); test_end(); } /* * Unseekable retry */ /* server */ static void test_unseekable_retry_input(struct server_connection *conn) { server_connection_deinit(&conn); } static void test_server_unseekable_retry(unsigned int index) { test_server_input = test_unseekable_retry_input; test_server_run(index); } /* client */ static void test_client_unseekable_retry_response( const struct http_response *resp, void *context ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_ABORTED); test_assert(resp->reason != NULL && *resp->reason != '\0'); io_loop_stop(ioloop); } static bool test_client_unseekable_retry(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct istream *input; http_client = http_client_init(client_set); input = i_stream_create_from_data("FROP", 4); input->seekable = FALSE; hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/unseekable-retry.txt", test_client_unseekable_retry_response, NULL); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, FALSE); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_unseekable_retry(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.max_attempts = 3; test_begin("unseekable retry"); test_run_client_server(&http_client_set, test_client_unseekable_retry, test_server_unseekable_retry, 2, NULL); test_end(); } /* * Broken payload */ /* server */ static void test_broken_payload_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 200 OK\r\n" "Content-Length: 18\r\n" "\r\n" "Everything is OK\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_broken_payload(unsigned int index) { test_server_input = test_broken_payload_input; test_server_run(index); } /* client */ static void test_client_broken_payload_response( const struct http_response *resp, void *context ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_BROKEN_PAYLOAD); test_assert(resp->reason != NULL && *resp->reason != '\0'); io_loop_stop(ioloop); } static bool test_client_broken_payload(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct istream *input; test_expect_errors(1); http_client = http_client_init(client_set); input = i_stream_create_error_str(EIO, "Moehahahaha!!"); i_stream_set_name(input, "PURE EVIL"); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/broken-payload.txt", test_client_broken_payload_response, NULL); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, FALSE); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_broken_payload(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("broken payload"); test_run_client_server(&http_client_set, test_client_broken_payload, test_server_broken_payload, 1, NULL); test_end(); } /* * Connection lost */ /* server */ static void test_connection_lost_input(struct server_connection *conn) { ssize_t ret; if (server_read_max == 0) { server_connection_deinit(&conn); return; } i_stream_set_max_buffer_size(conn->conn.input, server_read_max); ret = i_stream_read(conn->conn.input); if (ret == -2) { server_connection_deinit(&conn); return; } if (ret < 0) { if (i_stream_is_eof(conn->conn.input)) i_fatal("server: Client stream ended prematurely"); else i_fatal("server: Streem error: %s", i_stream_get_error(conn->conn.input)); } } static void test_server_connection_lost(unsigned int index) { test_server_input = test_connection_lost_input; test_server_run(index); } /* client */ struct _connection_lost_ctx { unsigned int count; }; struct _connection_lost_request_ctx { struct _connection_lost_ctx *ctx; struct http_client_request *req; }; static void test_client_connection_lost_response( const struct http_response *resp, struct _connection_lost_request_ctx *rctx) { struct _connection_lost_ctx *ctx = rctx->ctx; if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECTION_LOST); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (http_client_request_try_retry(rctx->req)) { if (debug) i_debug("retrying"); return; } i_free(rctx); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_connection_lost(const struct http_client_settings *client_set) { static const char payload[] = "This is a useless payload that only serves as a means to give the " "server the opportunity to close the connection before the payload " "is finished."; struct _connection_lost_ctx *ctx; struct _connection_lost_request_ctx *rctx; struct http_client_request *hreq; struct istream *input; ctx = i_new(struct _connection_lost_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); input = i_stream_create_from_data(payload, sizeof(payload)-1); rctx = i_new(struct _connection_lost_request_ctx, 1); rctx->ctx = ctx; rctx->req = hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost.txt", test_client_connection_lost_response, rctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, FALSE); http_client_request_submit(hreq); rctx = i_new(struct _connection_lost_request_ctx, 1); rctx->ctx = ctx; rctx->req = hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost2.txt", test_client_connection_lost_response, rctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_connection_lost(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); server_read_max = 0; test_begin("connection lost: one attempt"); http_client_set.max_attempts = 1; test_run_client_server(&http_client_set, test_client_connection_lost, test_server_connection_lost, 1, NULL); test_end(); test_begin("connection lost: two attempts"); http_client_set.max_attempts = 2; test_run_client_server(&http_client_set, test_client_connection_lost, test_server_connection_lost, 1, NULL); test_end(); test_begin("connection lost: three attempts"); http_client_set.max_attempts = 3; test_run_client_server(&http_client_set, test_client_connection_lost, test_server_connection_lost, 1, NULL); test_end(); test_begin("connection lost: manual retry"); http_client_set.max_attempts = 3; http_client_set.no_auto_retry = TRUE; test_run_client_server(&http_client_set, test_client_connection_lost, test_server_connection_lost, 1, NULL); test_end(); } /* * Connection lost after 100-continue */ /* server */ static void test_connection_lost_100_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 100 Continue\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_connection_lost_100(unsigned int index) { test_server_input = test_connection_lost_100_input; test_server_run(index); } /* client */ struct _connection_lost_100_ctx { unsigned int count; }; static void test_client_connection_lost_100_response( const struct http_response *resp, struct _connection_lost_100_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECTION_LOST); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_connection_lost_100( const struct http_client_settings *client_set) { static const char payload[] = "This is a useless payload that only serves as a means to give the " "server the opportunity to close the connection before the payload " "is finished."; struct _connection_lost_100_ctx *ctx; struct http_client_request *hreq; struct istream *input; ctx = i_new(struct _connection_lost_100_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); input = i_stream_create_from_data(payload, sizeof(payload)-1); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost.txt", test_client_connection_lost_100_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, TRUE); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost2.txt", test_client_connection_lost_100_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, TRUE); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_connection_lost_100(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); server_read_max = 0; test_begin("connection lost after 100-continue"); http_client_set.max_attempts = 1; test_run_client_server(&http_client_set, test_client_connection_lost_100, test_server_connection_lost_100, 1, NULL); test_end(); } /* * Connection lost in sub-ioloop */ /* server */ static void test_connection_lost_sub_ioloop_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 200 OK\r\n" "Content-Length: 0\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_connection_lost_sub_ioloop(unsigned int index) { test_server_input = test_connection_lost_sub_ioloop_input; test_server_run(index); } /* client */ struct _connection_lost_sub_ioloop_ctx { unsigned int count; }; static void test_client_connection_lost_sub_ioloop_response2( const struct http_response *resp, struct ioloop *sub_ioloop) { if (debug) i_debug("SUB-RESPONSE: %u %s", resp->status, resp->reason); io_loop_stop(sub_ioloop); } static void test_client_connection_lost_sub_ioloop_response( const struct http_response *resp, struct _connection_lost_sub_ioloop_ctx *ctx) { struct http_client_request *hreq; struct ioloop *sub_ioloop; if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == 200); test_assert(resp->reason != NULL && *resp->reason != '\0'); sub_ioloop = io_loop_create(); http_client_switch_ioloop(http_client); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost-sub-ioloop3.txt", test_client_connection_lost_sub_ioloop_response2, sub_ioloop); http_client_request_set_port(hreq, bind_ports[1]); http_client_request_submit(hreq); io_loop_run(sub_ioloop); io_loop_set_current(ioloop); http_client_switch_ioloop(http_client); io_loop_set_current(sub_ioloop); io_loop_destroy(&sub_ioloop); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_connection_lost_sub_ioloop( const struct http_client_settings *client_set) { static const char payload[] = "This is a useless payload that only serves as a means to give the " "server the opportunity to close the connection before the payload " "is finished."; struct _connection_lost_sub_ioloop_ctx *ctx; struct http_client_request *hreq; struct istream *input; ctx = i_new(struct _connection_lost_sub_ioloop_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); input = i_stream_create_from_data(payload, sizeof(payload)-1); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost-sub-ioloop.txt", test_client_connection_lost_sub_ioloop_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, TRUE); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/connection-lost-sub-ioloop2.txt", test_client_connection_lost_sub_ioloop_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_payload(hreq, input, TRUE); http_client_request_submit(hreq); i_stream_unref(&input); return TRUE; } /* test */ static void test_connection_lost_sub_ioloop(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); server_read_max = 0; test_begin("connection lost while running sub-ioloop"); http_client_set.max_attempts = 1; test_run_client_server(&http_client_set, test_client_connection_lost_sub_ioloop, test_server_connection_lost_sub_ioloop, 2, NULL); test_end(); } /* * Early success */ /* server */ static void test_early_success_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 200 OK\r\n" "Content-Length: 18\r\n" "\r\n" "Everything is OK\r\n"; usleep(200000); o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_early_success(unsigned int index) { test_server_input = test_early_success_input; test_server_run(index); } /* client */ struct _early_success_ctx { unsigned int count; }; static void test_client_early_success_response( const struct http_response *resp, struct _early_success_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); if (ctx->count == 2) test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_BAD_RESPONSE); else test_assert(resp->status == 200); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { io_loop_stop(ioloop); i_free(ctx); } } static bool test_client_early_success(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _early_success_ctx *ctx; string_t *payload; unsigned int i; ctx = i_new(struct _early_success_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/early-success.txt", test_client_early_success_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); T_BEGIN { struct istream_chain *chain; struct istream *input, *chain_input; payload = t_str_new(64*3000); for (i = 0; i < 3000; i++) { str_append(payload, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n"); } chain_input = i_stream_create_chain(&chain); input = i_stream_create_copy_from_data (str_data(payload), str_len(payload)); i_stream_chain_append(chain, input); i_stream_unref(&input); http_client_request_set_payload(hreq, chain_input, FALSE); i_stream_unref(&chain_input); } T_END; http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/early-success2.txt", test_client_early_success_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_early_success(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.socket_send_buffer_size = 4096; test_begin("early succes"); test_run_client_server(&http_client_set, test_client_early_success, test_server_early_success, 1, NULL); test_end(); } /* * Bad response */ /* server */ static void test_bad_response_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 666 Really bad response\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_bad_response(unsigned int index) { test_server_input = test_bad_response_input; test_server_run(index); } /* client */ struct _bad_response_ctx { unsigned int count; }; static void test_client_bad_response_response( const struct http_response *resp, struct _bad_response_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_BAD_RESPONSE); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_bad_response(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _bad_response_ctx *ctx; ctx = i_new(struct _bad_response_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/bad-response.txt", test_client_bad_response_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/bad-response2.txt", test_client_bad_response_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_bad_response(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("bad response"); test_run_client_server(&http_client_set, test_client_bad_response, test_server_bad_response, 1, NULL); test_end(); } /* * Request timed out */ /* server */ static void test_request_timed_out_input(struct server_connection *conn ATTR_UNUSED) { /* do nothing */ } static void test_server_request_timed_out(unsigned int index) { test_server_input = test_request_timed_out_input; test_server_run(index); } /* client */ struct _request_timed_out1_ctx { unsigned int count; }; static void test_client_request_timed_out1_response( const struct http_response *resp, struct _request_timed_out1_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_TIMED_OUT); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_request_timed_out1(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _request_timed_out1_ctx *ctx; ctx = i_new(struct _request_timed_out1_ctx, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-timed-out1-1.txt", test_client_request_timed_out1_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-timed-out1-2.txt", test_client_request_timed_out1_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } struct _request_timed_out2_ctx { struct timeout *to; unsigned int count; unsigned int max_parallel_connections; }; static void test_client_request_timed_out2_timeout( struct _request_timed_out2_ctx *ctx) { if (ctx->to != NULL) timeout_remove(&ctx->to); i_debug("TIMEOUT"); } static void test_client_request_timed_out2_response( const struct http_response *resp, struct _request_timed_out2_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_TIMED_OUT); test_assert(resp->reason != NULL && *resp->reason != '\0'); test_assert(ctx->to != NULL); if (--ctx->count > 0) { if (ctx->to != NULL && ctx->max_parallel_connections <= 1) timeout_reset(ctx->to); } else { if (ctx->to != NULL) timeout_remove(&ctx->to); i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_request_timed_out2(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _request_timed_out2_ctx *ctx; ctx = i_new(struct _request_timed_out2_ctx, 1); ctx->count = 2; ctx->max_parallel_connections = client_set->max_parallel_connections; ctx->to = timeout_add(2000, test_client_request_timed_out2_timeout, ctx); http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-timed-out2-1.txt", test_client_request_timed_out2_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_attempt_timeout_msecs(hreq, 1000); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-timed-out2-2.txt", test_client_request_timed_out2_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_set_attempt_timeout_msecs(hreq, 1000); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_request_timed_out(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("request timed out: one attempt"); http_client_set.request_timeout_msecs = 1000; http_client_set.max_attempts = 1; test_run_client_server(&http_client_set, test_client_request_timed_out1, test_server_request_timed_out, 1, NULL); test_end(); test_begin("request timed out: two attempts"); http_client_set.request_timeout_msecs = 1000; http_client_set.max_attempts = 1; test_run_client_server(&http_client_set, test_client_request_timed_out1, test_server_request_timed_out, 1, NULL); test_end(); test_begin("request absolutely timed out"); http_client_set.request_timeout_msecs = 0; http_client_set.request_absolute_timeout_msecs = 2000; http_client_set.max_attempts = 3; test_run_client_server(&http_client_set, test_client_request_timed_out1, test_server_request_timed_out, 1, NULL); test_end(); test_begin("request double timed out"); http_client_set.request_timeout_msecs = 500; http_client_set.request_absolute_timeout_msecs = 2000; http_client_set.max_attempts = 3; test_run_client_server(&http_client_set, test_client_request_timed_out1, test_server_request_timed_out, 1, NULL); test_end(); test_begin("request timed out: specific timeout"); http_client_set.request_timeout_msecs = 3000; http_client_set.request_absolute_timeout_msecs = 0; http_client_set.max_attempts = 1; http_client_set.max_parallel_connections = 1; test_run_client_server(&http_client_set, test_client_request_timed_out2, test_server_request_timed_out, 1, NULL); test_end(); test_begin("request timed out: specific timeout (parallel)"); http_client_set.request_timeout_msecs = 3000; http_client_set.request_absolute_timeout_msecs = 0; http_client_set.max_attempts = 1; http_client_set.max_parallel_connections = 4; test_run_client_server(&http_client_set, test_client_request_timed_out2, test_server_request_timed_out, 1, NULL); test_end(); } /* * Request aborted early */ /* server */ static void test_request_aborted_early_input(struct server_connection *conn ATTR_UNUSED) { static const char *resp = "HTTP/1.1 404 Not Found\r\n" "\r\n"; /* wait one second to respon */ sleep(1); /* respond */ o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_request_aborted_early(unsigned int index) { test_server_input = test_request_aborted_early_input; test_server_run(index); } /* client */ struct _request_aborted_early_ctx { struct http_client_request *req1, *req2; struct timeout *to; }; static void test_client_request_aborted_early_response( const struct http_response *resp, struct _request_aborted_early_ctx *ctx ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); /* abort does not trigger callback */ test_assert(FALSE); } static void test_client_request_aborted_early_timeout( struct _request_aborted_early_ctx *ctx) { timeout_remove(&ctx->to); if (ctx->req1 != NULL) { /* abort early */ http_client_request_abort(&ctx->req1); /* sent */ http_client_request_abort(&ctx->req2); /* only queued */ /* wait a little for server to actually respond to an already aborted request */ ctx->to = timeout_add_short(1000, test_client_request_aborted_early_timeout, ctx); } else { /* all done */ i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_request_aborted_early( const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _request_aborted_early_ctx *ctx; ctx = i_new(struct _request_aborted_early_ctx, 1); http_client = http_client_init(client_set); hreq = ctx->req1 = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-aborted-early.txt", test_client_request_aborted_early_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = ctx->req2 = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-aborted-early2.txt", test_client_request_aborted_early_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); ctx->to = timeout_add_short(500, test_client_request_aborted_early_timeout, ctx); return TRUE; } /* test */ static void test_request_aborted_early(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("request aborted early"); test_run_client_server(&http_client_set, test_client_request_aborted_early, test_server_request_aborted_early, 1, NULL); test_end(); } /* * Request failed blocking */ /* server */ static void test_request_failed_blocking_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 500 Internal Server Error\r\n" "\r\n"; /* respond */ o_stream_nsend_str(conn->conn.output, resp); sleep(10); server_connection_deinit(&conn); } static void test_server_request_failed_blocking(unsigned int index) { test_server_input = test_request_failed_blocking_input; test_server_run(index); } /* client */ struct _request_failed_blocking_ctx { struct http_client_request *req; }; static void test_client_request_failed_blocking_response( const struct http_response *resp, struct _request_failed_blocking_ctx *ctx ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); i_assert(resp->status == 500); } static bool test_client_request_failed_blocking( const struct http_client_settings *client_set) { static const char *payload = "This a test payload!"; struct http_client_request *hreq; struct _request_failed_blocking_ctx *ctx; unsigned int n; string_t *data; data = str_new(default_pool, 1000000); for (n = 0; n < 50000; n++) str_append(data, payload); ctx = i_new(struct _request_failed_blocking_ctx, 1); http_client = http_client_init(client_set); hreq = ctx->req = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/request-failed-blocking.txt", test_client_request_failed_blocking_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); test_assert(http_client_request_send_payload(&hreq, str_data(data), str_len(data)) < 0); i_assert(hreq == NULL); str_free(&data); i_free(ctx); return FALSE; } /* test */ static void test_request_failed_blocking(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.socket_send_buffer_size = 4096; test_begin("request failed blocking"); test_run_client_server(&http_client_set, test_client_request_failed_blocking, test_server_request_failed_blocking, 1, NULL); test_end(); } /* * Client deinit early */ /* server */ static void test_client_deinit_early_input(struct server_connection *conn ATTR_UNUSED) { static const char *resp = "HTTP/1.1 404 Not Found\r\n" "\r\n"; /* wait one second to respon */ sleep(1); /* respond */ o_stream_nsend_str(conn->conn.output, resp); server_connection_deinit(&conn); } static void test_server_client_deinit_early(unsigned int index) { test_server_input = test_client_deinit_early_input; test_server_run(index); } /* client */ struct _client_deinit_early_ctx { struct timeout *to; }; static void test_client_client_deinit_early_response( const struct http_response *resp, struct _client_deinit_early_ctx *ctx ATTR_UNUSED) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); /* abort does not trigger callback */ test_assert(FALSE); } static void test_client_client_deinit_early_timeout( struct _client_deinit_early_ctx *ctx) { timeout_remove(&ctx->to); /* deinit early */ http_client_deinit(&http_client); /* all done */ i_free(ctx); io_loop_stop(ioloop); } static bool test_client_client_deinit_early(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _client_deinit_early_ctx *ctx; ctx = i_new(struct _client_deinit_early_ctx, 1); http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/client-deinit-early.txt", test_client_client_deinit_early_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/client-deinit-early2.txt", test_client_client_deinit_early_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); ctx->to = timeout_add_short(500, test_client_client_deinit_early_timeout, ctx); return TRUE; } /* test */ static void test_client_deinit_early(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); test_begin("client deinit early"); test_run_client_server(&http_client_set, test_client_client_deinit_early, test_server_client_deinit_early, 1, NULL); test_end(); } /* * Retry with delay */ /* server */ static void test_retry_with_delay_input(struct server_connection *conn) { string_t *resp; resp = t_str_new(512); str_printfa(resp, "HTTP/1.1 500 Internal Server Error\r\n" "\r\n"); o_stream_nsend(conn->conn.output, str_data(resp), str_len(resp)); server_connection_deinit(&conn); } static void test_server_retry_with_delay(unsigned int index) { test_server_input = test_retry_with_delay_input; test_server_run(index); } /* client */ struct _client_retry_with_delay_ctx { struct http_client_request *req; unsigned int retries; struct timeval time; }; static void test_client_retry_with_delay_response( const struct http_response *resp, struct _client_retry_with_delay_ctx *ctx) { int real_delay, exp_delay; if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == 500); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (ctx->retries > 0) { /* check delay */ real_delay = timeval_diff_msecs(&ioloop_timeval, &ctx->time); exp_delay = (1 << (ctx->retries-1)) * 50; if (real_delay < exp_delay-2) { i_fatal("Retry delay is too short %d < %d", real_delay, exp_delay); } } http_client_request_delay_msecs(ctx->req, (1 << ctx->retries) * 50); ctx->time = ioloop_timeval; if (http_client_request_try_retry(ctx->req)) { ctx->retries++; if (debug) i_debug("retrying"); return; } i_free(ctx); io_loop_stop(ioloop); } static bool test_client_retry_with_delay(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _client_retry_with_delay_ctx *ctx; ctx = i_new(struct _client_retry_with_delay_ctx, 1); ctx->time = ioloop_timeval; http_client = http_client_init(client_set); ctx->req = hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/retry-with-delay.txt", test_client_retry_with_delay_response, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_retry_with_delay(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.max_attempts = 3; test_begin("retry with delay"); test_run_client_server(&http_client_set, test_client_retry_with_delay, test_server_retry_with_delay, 1, NULL); test_end(); } /* * DNS service failure */ /* client */ struct _dns_service_failure { unsigned int count; }; static void test_client_dns_service_failure_response( const struct http_response *resp, struct _dns_service_failure *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_dns_service_failure(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _dns_service_failure *ctx; ctx = i_new(struct _dns_service_failure, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "example.com", "/dns-service-failure.txt", test_client_dns_service_failure_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "example.com", "/dns-service-failure2.txt", test_client_dns_service_failure_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_dns_service_failure(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.dns_client_socket_path = "./frop"; test_begin("dns service failure"); test_run_client_server(&http_client_set, test_client_dns_service_failure, NULL, 0, NULL); test_end(); } /* * DNS timeout */ /* dns */ static void test_dns_timeout_input(struct server_connection *conn ATTR_UNUSED) { /* hang */ sleep(100); server_connection_deinit(&conn); } static void test_dns_dns_timeout(void) { test_server_input = test_dns_timeout_input; test_server_run(0); } /* client */ struct _dns_timeout { unsigned int count; }; static void test_client_dns_timeout_response( const struct http_response *resp, struct _dns_timeout *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_dns_timeout(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _dns_timeout *ctx; ctx = i_new(struct _dns_timeout, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "example.com", "/dns-timeout.txt", test_client_dns_timeout_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "example.com", "/dns-timeout2.txt", test_client_dns_timeout_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_dns_timeout(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.request_timeout_msecs = 2000; http_client_set.connect_timeout_msecs = 2000; http_client_set.dns_client_socket_path = "./dns-test"; test_begin("dns timeout"); test_run_client_server(&http_client_set, test_client_dns_timeout, NULL, 0, test_dns_dns_timeout); test_end(); } /* * DNS lookup failure */ /* dns */ static void test_dns_lookup_failure_input(struct server_connection *conn) { o_stream_nsend_str(conn->conn.output, t_strdup_printf("%d\n", EAI_FAIL)); server_connection_deinit(&conn); } static void test_dns_dns_lookup_failure(void) { test_server_input = test_dns_lookup_failure_input; test_server_run(0); } /* client */ struct _dns_lookup_failure { unsigned int count; }; static void test_client_dns_lookup_failure_response( const struct http_response *resp, struct _dns_lookup_failure *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static bool test_client_dns_lookup_failure(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _dns_lookup_failure *ctx; ctx = i_new(struct _dns_lookup_failure, 1); ctx->count = 2; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "example.com", "/dns-lookup-failure.txt", test_client_dns_lookup_failure_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", "example.com", "/dns-lookup-failure2.txt", test_client_dns_lookup_failure_response, ctx); http_client_request_set_port(hreq, 80); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_dns_lookup_failure(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.dns_client_socket_path = "./dns-test"; test_begin("dns lookup failure"); test_run_client_server(&http_client_set, test_client_dns_lookup_failure, NULL, 0, test_dns_dns_lookup_failure); test_end(); } /* * DNS lookup ttl */ /* dns */ static void test_dns_lookup_ttl_input(struct server_connection *conn) { static unsigned int count = 0; const char *line; while ((line=i_stream_read_next_line(conn->conn.input)) != NULL) { if (debug) i_debug("DNS REQUEST %u: %s", count, line); if (count == 0) { o_stream_nsend_str(conn->conn.output, "0 1\n127.0.0.1\n"); } else { o_stream_nsend_str(conn->conn.output, t_strdup_printf("%d\n", EAI_FAIL)); if (count > 4) { server_connection_deinit(&conn); return; } } count++; } } static void test_dns_dns_lookup_ttl(void) { test_server_input = test_dns_lookup_ttl_input; test_server_run(0); } /* server */ static void test_server_dns_lookup_ttl_input(struct server_connection *conn) { string_t *resp; resp = t_str_new(512); str_printfa(resp, "HTTP/1.1 200 OK\r\n" "Connection: close\r\n" "\r\n"); o_stream_nsend(conn->conn.output, str_data(resp), str_len(resp)); server_connection_deinit(&conn); } static void test_server_dns_lookup_ttl(unsigned int index) { test_server_input = test_server_dns_lookup_ttl_input; test_server_run(index); } /* client */ struct _dns_lookup_ttl { struct http_client *client; unsigned int count; struct timeout *to; }; static void test_client_dns_lookup_ttl_response_stage2( const struct http_response *resp, struct _dns_lookup_ttl *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_HOST_LOOKUP_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); if (--ctx->count == 0) { i_free(ctx); io_loop_stop(ioloop); } } static void test_client_dns_lookup_ttl_stage2_start(struct _dns_lookup_ttl *ctx) { struct http_client_request *hreq; timeout_remove(&ctx->to); ctx->count = 2; hreq = http_client_request(ctx->client, "GET", "example.com", "/dns-lookup-ttl-stage2.txt", test_client_dns_lookup_ttl_response_stage2, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(ctx->client, "GET", "example.com", "/dns-lookup-ttl2-stage2.txt", test_client_dns_lookup_ttl_response_stage2, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); } static void test_client_dns_lookup_ttl_response_stage1( const struct http_response *resp, struct _dns_lookup_ttl *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == 200); if (--ctx->count == 0) { ctx->to = timeout_add(2000, test_client_dns_lookup_ttl_stage2_start, ctx); } } static bool test_client_dns_lookup_ttl(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _dns_lookup_ttl *ctx; ctx = i_new(struct _dns_lookup_ttl, 1); ctx->count = 2; ctx->client = http_client = http_client_init(client_set); hreq = http_client_request(ctx->client, "GET", "example.com", "/dns-lookup-ttl-stage1.txt", test_client_dns_lookup_ttl_response_stage1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(ctx->client, "GET", "example.com", "/dns-lookup-ttl2-stage1.txt", test_client_dns_lookup_ttl_response_stage1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_dns_lookup_ttl(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.dns_client_socket_path = "./dns-test"; http_client_set.dns_ttl_msecs = 1000; test_begin("dns lookup ttl"); test_run_client_server(&http_client_set, test_client_dns_lookup_ttl, test_server_dns_lookup_ttl, 1, test_dns_dns_lookup_ttl); test_end(); } /* * Peer reuse failure */ /* server */ static void test_peer_reuse_failure_input(struct server_connection *conn) { static unsigned int seq = 0; static const char *resp = "HTTP/1.1 200 OK\r\n" "\r\n"; o_stream_nsend_str(conn->conn.output, resp); if (seq++ > 2) { server_connection_deinit(&conn); io_loop_stop(current_ioloop); } } static void test_server_peer_reuse_failure(unsigned int index) { test_server_input = test_peer_reuse_failure_input; test_server_run(index); } /* client */ struct _peer_reuse_failure { struct timeout *to; bool first:1; }; static void test_client_peer_reuse_failure_response2( const struct http_response *resp, struct _peer_reuse_failure *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); i_free(ctx); io_loop_stop(ioloop); } static void test_client_peer_reuse_failure_next(struct _peer_reuse_failure *ctx) { struct http_client_request *hreq; timeout_remove(&ctx->to); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/peer-reuse-next.txt", test_client_peer_reuse_failure_response2, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); } static void test_client_peer_reuse_failure_response1( const struct http_response *resp, struct _peer_reuse_failure *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); if (ctx->first) { test_assert(resp->status == 200); ctx->first = FALSE; ctx->to = timeout_add_short(500, test_client_peer_reuse_failure_next, ctx); } else { test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); } test_assert(resp->reason != NULL && *resp->reason != '\0'); } static bool test_client_peer_reuse_failure(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _peer_reuse_failure *ctx; ctx = i_new(struct _peer_reuse_failure, 1); ctx->first = TRUE; http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/peer-reuse.txt", test_client_peer_reuse_failure_response1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/peer-reuse.txt", test_client_peer_reuse_failure_response1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); hreq = http_client_request(http_client, "GET", net_ip2addr(&bind_ip), "/peer-reuse.txt", test_client_peer_reuse_failure_response1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_peer_reuse_failure(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.max_connect_attempts = 1; http_client_set.max_idle_time_msecs = 500; test_begin("peer reuse failure"); test_run_client_server(&http_client_set, test_client_peer_reuse_failure, test_server_peer_reuse_failure, 1, NULL); test_end(); } /* * Reconnect failure */ /* dns */ static void test_dns_reconnect_failure_input(struct server_connection *conn) { static unsigned int count = 0; const char *line; while ((line=i_stream_read_next_line(conn->conn.input)) != NULL) { if (debug) i_debug("DNS REQUEST %u: %s", count, line); if (count == 0) { o_stream_nsend_str(conn->conn.output, "0 1\n127.0.0.1\n"); } else { o_stream_nsend_str(conn->conn.output, t_strdup_printf("%d\n", EAI_FAIL)); if (count > 4) { server_connection_deinit(&conn); return; } } count++; } } static void test_dns_reconnect_failure(void) { test_server_input = test_dns_reconnect_failure_input; test_server_run(0); } /* server */ static void test_reconnect_failure_input(struct server_connection *conn) { static const char *resp = "HTTP/1.1 200 OK\r\n" "Content-Length: 18\r\n" "\r\n" "Everything is OK\r\n"; o_stream_nsend_str(conn->conn.output, resp); i_close_fd(&fd_listen); sleep(500); } static void test_server_reconnect_failure(unsigned int index) { test_server_input = test_reconnect_failure_input; test_server_run(index); } /* client */ struct _reconnect_failure_ctx { struct timeout *to; }; static void test_client_reconnect_failure_response2( const struct http_response *resp, struct _reconnect_failure_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == HTTP_CLIENT_REQUEST_ERROR_CONNECT_FAILED); test_assert(resp->reason != NULL && *resp->reason != '\0'); io_loop_stop(ioloop); i_free(ctx); } static void test_client_reconnect_failure_next( struct _reconnect_failure_ctx *ctx) { struct http_client_request *hreq; if (debug) i_debug("NEXT REQUEST"); timeout_remove(&ctx->to); hreq = http_client_request(http_client, "GET", "example.com", "/reconnect-failure-2.txt", test_client_reconnect_failure_response2, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); } static void test_client_reconnect_failure_response1( const struct http_response *resp, struct _reconnect_failure_ctx *ctx) { if (debug) i_debug("RESPONSE: %u %s", resp->status, resp->reason); test_assert(resp->status == 200); test_assert(resp->reason != NULL && *resp->reason != '\0'); ctx->to = timeout_add_short(999, test_client_reconnect_failure_next, ctx); } static bool test_client_reconnect_failure(const struct http_client_settings *client_set) { struct http_client_request *hreq; struct _reconnect_failure_ctx *ctx; ctx = i_new(struct _reconnect_failure_ctx, 1); http_client = http_client_init(client_set); hreq = http_client_request(http_client, "GET", "example.com", "/reconnect-failure-1.txt", test_client_reconnect_failure_response1, ctx); http_client_request_set_port(hreq, bind_ports[0]); http_client_request_submit(hreq); return TRUE; } /* test */ static void test_reconnect_failure(void) { struct http_client_settings http_client_set; test_client_defaults(&http_client_set); http_client_set.dns_client_socket_path = "./dns-test"; http_client_set.dns_ttl_msecs = 2000; http_client_set.max_idle_time_msecs = 1000; http_client_set.max_attempts = 1; http_client_set.request_timeout_msecs = 1000; test_begin("reconnect failure"); test_run_client_server(&http_client_set, test_client_reconnect_failure, test_server_reconnect_failure, 1, test_dns_reconnect_failure); test_end(); } /* * All tests */ static void (*test_functions[])(void) = { test_unconfigured_ssl, test_unconfigured_ssl_abort, test_invalid_url, test_host_lookup_failed, test_connection_refused, test_connection_lost_prematurely, test_connection_timed_out, test_invalid_redirect, test_unseekable_redirect, test_unseekable_retry, test_broken_payload, test_connection_lost, test_connection_lost_100, test_connection_lost_sub_ioloop, test_early_success, test_bad_response, test_request_timed_out, test_request_aborted_early, test_request_failed_blocking, test_client_deinit_early, test_retry_with_delay, test_dns_service_failure, test_dns_timeout, test_dns_lookup_failure, test_dns_lookup_ttl, test_peer_reuse_failure, test_reconnect_failure, NULL }; /* * Test client */ static void test_client_defaults(struct http_client_settings *http_set) { /* client settings */ i_zero(http_set); http_set->max_idle_time_msecs = 5*1000; http_set->max_parallel_connections = 1; http_set->max_pipelined_requests = 1; http_set->max_redirects = 0; http_set->max_attempts = 1; http_set->debug = debug; } static void test_client_deinit(void) { if (http_client != NULL) http_client_deinit(&http_client); http_client = NULL; } /* * Test server */ /* client connection */ static void server_connection_input(struct connection *_conn) { struct server_connection *conn = (struct server_connection *)_conn; test_server_input(conn); } static void server_connection_init(int fd) { struct server_connection *conn; pool_t pool; net_set_nonblock(fd, TRUE); pool = pool_alloconly_create("server connection", 256); conn = p_new(pool, struct server_connection, 1); conn->pool = pool; connection_init_server (server_conn_list, &conn->conn, "server connection", fd, fd); } static void server_connection_deinit(struct server_connection **_conn) { struct server_connection *conn = *_conn; *_conn = NULL; connection_deinit(&conn->conn); pool_unref(&conn->pool); } static void server_connection_destroy(struct connection *_conn) { struct server_connection *conn = (struct server_connection *)_conn; server_connection_deinit(&conn); } static void server_connection_accept(void *context ATTR_UNUSED) { int fd; /* accept new client */ fd = net_accept(fd_listen, NULL, NULL); if (fd == -1) return; if (fd == -2) { i_fatal("test server: accept() failed: %m"); } server_connection_init(fd); } /* */ static struct connection_settings server_connection_set = { .input_max_size = (size_t)-1, .output_max_size = (size_t)-1, .client = FALSE }; static const struct connection_vfuncs server_connection_vfuncs = { .destroy = server_connection_destroy, .input = server_connection_input }; static void test_server_run(unsigned int index) { server_index = index; /* open server socket */ io_listen = io_add(fd_listen, IO_READ, server_connection_accept, (void *)NULL); server_conn_list = connection_list_init (&server_connection_set, &server_connection_vfuncs); io_loop_run(ioloop); /* close server socket */ io_remove(&io_listen); connection_list_deinit(&server_conn_list); } /* * Tests */ static int test_open_server_fd(in_port_t *bind_port) { int fd = net_listen(&bind_ip, bind_port, 128); if (debug) i_debug("server listening on %u", *bind_port); if (fd == -1) { i_fatal("listen(%s:%u) failed: %m", net_ip2addr(&bind_ip), *bind_port); } return fd; } static void test_servers_kill_all(void) { unsigned int i; if (server_pids_count > 0) { for (i = 0; i < server_pids_count; i++) { if (server_pids[i] != (pid_t)-1) { (void)kill(server_pids[i], SIGKILL); (void)waitpid(server_pids[i], NULL, 0); server_pids[i] = -1; } } } server_pids_count = 0; if (dns_pid != (pid_t)-1) { (void)kill(dns_pid, SIGKILL); (void)waitpid(dns_pid, NULL, 0); dns_pid = (pid_t)-1; } } static void test_run_client_server( const struct http_client_settings *client_set, test_client_init_t client_test, test_server_init_t server_test, unsigned int server_tests_count, test_dns_init_t dns_test) { unsigned int i; server_pids = NULL; server_pids_count = 0; if (server_tests_count > 0) { int fds[server_tests_count]; bind_ports = i_new(in_port_t, server_tests_count); server_pids = i_new(pid_t, server_tests_count); for (i = 0; i < server_tests_count; i++) server_pids[i] = (pid_t)-1; server_pids_count = server_tests_count; for (i = 0; i < server_tests_count; i++) fds[i] = test_open_server_fd(&bind_ports[i]); for (i = 0; i < server_tests_count; i++) { fd_listen = fds[i]; if ((server_pids[i] = fork()) == (pid_t)-1) i_fatal("fork() failed: %m"); if (server_pids[i] == 0) { server_pids[i] = (pid_t)-1; server_pids_count = 0; hostpid_init(); if (debug) i_debug("server[%d]: PID=%s", i+1, my_pid); /* child: server */ ioloop = io_loop_create(); server_test(i); io_loop_destroy(&ioloop); if (fd_listen != -1) i_close_fd(&fd_listen); i_free(bind_ports); i_free(server_pids); /* wait for it to be killed; this way, valgrind will not object to this process going away inelegantly. */ sleep(60); exit(1); } if (fd_listen != -1) i_close_fd(&fd_listen); } if (debug) i_debug("client: PID=%s", my_pid); } if (dns_test != NULL) { int fd; i_unlink_if_exists("./dns-test"); fd = net_listen_unix("./dns-test", 128); if (fd == -1) { i_fatal("listen(./dns-test) failed: %m"); } fd_listen = fd; if ((dns_pid = fork()) == (pid_t)-1) i_fatal("fork() failed: %m"); if (dns_pid == 0) { dns_pid = (pid_t)-1; hostpid_init(); if (debug) i_debug("dns server: PID=%s", my_pid); /* child: server */ ioloop = io_loop_create(); dns_test(); io_loop_destroy(&ioloop); if (fd_listen != -1) i_close_fd(&fd_listen); /* wait for it to be killed; this way, valgrind will not object to this process going away inelegantly. */ sleep(60); exit(1); } if (fd_listen != -1) i_close_fd(&fd_listen); } /* parent: client */ usleep(100000); /* wait a little for server setup */ ioloop = io_loop_create(); if (client_test(client_set)) io_loop_run(ioloop); test_client_deinit(); io_loop_destroy(&ioloop); test_servers_kill_all(); i_free(server_pids); i_free(bind_ports); i_unlink_if_exists("./dns-test"); } /* * Main */ volatile sig_atomic_t terminating = 0; static void test_signal_handler(int signo) { if (terminating) raise(signo); terminating = 1; /* make sure we don't leave any pesky children alive */ test_servers_kill_all(); (void)signal(signo, SIG_DFL); raise(signo); } static void test_atexit(void) { test_servers_kill_all(); } int main(int argc, char *argv[]) { int c; atexit(test_atexit); (void)signal(SIGCHLD, SIG_IGN); (void)signal(SIGTERM, test_signal_handler); (void)signal(SIGQUIT, test_signal_handler); (void)signal(SIGINT, test_signal_handler); (void)signal(SIGSEGV, test_signal_handler); (void)signal(SIGABRT, test_signal_handler); while ((c = getopt(argc, argv, "D")) > 0) { switch (c) { case 'D': debug = TRUE; break; default: i_fatal("Usage: %s [-D]", argv[0]); } } /* listen on localhost */ i_zero(&bind_ip); bind_ip.family = AF_INET; bind_ip.u.ip4.s_addr = htonl(INADDR_LOOPBACK); test_run(test_functions); }
22.907532
86
0.757031
[ "object" ]
a50b9f2a211dc8952c7114c4112b9a6ae3db3ff5
7,133
h
C
deps/museum/7.0.0/art/runtime/mirror/dex_cache-inl.h
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
deps/museum/7.0.0/art/runtime/mirror/dex_cache-inl.h
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
deps/museum/7.0.0/art/runtime/mirror/dex_cache-inl.h
simpleton/profilo
91ef4ba1a8316bad2b3080210316dfef4761e180
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ART_RUNTIME_MIRROR_DEX_CACHE_INL_H_ #define ART_RUNTIME_MIRROR_DEX_CACHE_INL_H_ #include <museum/7.0.0/art/runtime/mirror/dex_cache.h> #include <museum/7.0.0/art/runtime/art_field-inl.h> #include <museum/7.0.0/art/runtime/art_method-inl.h> #include <museum/7.0.0/art/runtime/base/casts.h> #include <museum/7.0.0/art/runtime/base/logging.h> #include <museum/7.0.0/art/runtime/mirror/class.h> #include <museum/7.0.0/art/runtime/runtime.h> namespace facebook { namespace museum { namespace MUSEUM_VERSION { namespace art { namespace mirror { inline uint32_t DexCache::ClassSize(size_t pointer_size) { uint32_t vtable_entries = Object::kVTableLength + 5; return Class::ComputeClassSize(true, vtable_entries, 0, 0, 0, 0, 0, pointer_size); } inline String* DexCache::GetResolvedString(uint32_t string_idx) { DCHECK_LT(string_idx, NumStrings()); return GetStrings()[string_idx].Read(); } inline void DexCache::SetResolvedString(uint32_t string_idx, String* resolved) { DCHECK_LT(string_idx, NumStrings()); // TODO default transaction support. GetStrings()[string_idx] = GcRoot<String>(resolved); // TODO: Fine-grained marking, so that we don't need to go through all arrays in full. Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(this); } inline Class* DexCache::GetResolvedType(uint32_t type_idx) { DCHECK_LT(type_idx, NumResolvedTypes()); return GetResolvedTypes()[type_idx].Read(); } inline void DexCache::SetResolvedType(uint32_t type_idx, Class* resolved) { DCHECK_LT(type_idx, NumResolvedTypes()); // NOTE: Unchecked, i.e. not throwing AIOOB. // TODO default transaction support. GetResolvedTypes()[type_idx] = GcRoot<Class>(resolved); // TODO: Fine-grained marking, so that we don't need to go through all arrays in full. Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(this); } inline ArtField* DexCache::GetResolvedField(uint32_t field_idx, size_t ptr_size) { DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), ptr_size); DCHECK_LT(field_idx, NumResolvedFields()); // NOTE: Unchecked, i.e. not throwing AIOOB. ArtField* field = GetElementPtrSize(GetResolvedFields(), field_idx, ptr_size); if (field == nullptr || field->GetDeclaringClass()->IsErroneous()) { return nullptr; } return field; } inline void DexCache::SetResolvedField(uint32_t field_idx, ArtField* field, size_t ptr_size) { DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), ptr_size); DCHECK_LT(field_idx, NumResolvedFields()); // NOTE: Unchecked, i.e. not throwing AIOOB. SetElementPtrSize(GetResolvedFields(), field_idx, field, ptr_size); } inline ArtMethod* DexCache::GetResolvedMethod(uint32_t method_idx, size_t ptr_size) { DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), ptr_size); DCHECK_LT(method_idx, NumResolvedMethods()); // NOTE: Unchecked, i.e. not throwing AIOOB. ArtMethod* method = GetElementPtrSize<ArtMethod*>(GetResolvedMethods(), method_idx, ptr_size); // Hide resolution trampoline methods from the caller if (method != nullptr && method->IsRuntimeMethod()) { DCHECK_EQ(method, Runtime::Current()->GetResolutionMethod()); return nullptr; } return method; } inline void DexCache::SetResolvedMethod(uint32_t method_idx, ArtMethod* method, size_t ptr_size) { DCHECK_EQ(Runtime::Current()->GetClassLinker()->GetImagePointerSize(), ptr_size); DCHECK_LT(method_idx, NumResolvedMethods()); // NOTE: Unchecked, i.e. not throwing AIOOB. SetElementPtrSize(GetResolvedMethods(), method_idx, method, ptr_size); } template <typename PtrType> inline PtrType DexCache::GetElementPtrSize(PtrType* ptr_array, size_t idx, size_t ptr_size) { if (ptr_size == 8u) { uint64_t element = reinterpret_cast<const uint64_t*>(ptr_array)[idx]; return reinterpret_cast<PtrType>(dchecked_integral_cast<uintptr_t>(element)); } else { DCHECK_EQ(ptr_size, 4u); uint32_t element = reinterpret_cast<const uint32_t*>(ptr_array)[idx]; return reinterpret_cast<PtrType>(dchecked_integral_cast<uintptr_t>(element)); } } template <typename PtrType> inline void DexCache::SetElementPtrSize(PtrType* ptr_array, size_t idx, PtrType ptr, size_t ptr_size) { if (ptr_size == 8u) { reinterpret_cast<uint64_t*>(ptr_array)[idx] = dchecked_integral_cast<uint64_t>(reinterpret_cast<uintptr_t>(ptr)); } else { DCHECK_EQ(ptr_size, 4u); reinterpret_cast<uint32_t*>(ptr_array)[idx] = dchecked_integral_cast<uint32_t>(reinterpret_cast<uintptr_t>(ptr)); } } template <bool kVisitNativeRoots, VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption, typename Visitor> inline void DexCache::VisitReferences(mirror::Class* klass, const Visitor& visitor) { // Visit instance fields first. VisitInstanceFieldsReferences<kVerifyFlags, kReadBarrierOption>(klass, visitor); // Visit arrays after. if (kVisitNativeRoots) { GcRoot<mirror::String>* strings = GetStrings(); for (size_t i = 0, num_strings = NumStrings(); i != num_strings; ++i) { visitor.VisitRootIfNonNull(strings[i].AddressWithoutBarrier()); } GcRoot<mirror::Class>* resolved_types = GetResolvedTypes(); for (size_t i = 0, num_types = NumResolvedTypes(); i != num_types; ++i) { visitor.VisitRootIfNonNull(resolved_types[i].AddressWithoutBarrier()); } } } template <ReadBarrierOption kReadBarrierOption, typename Visitor> inline void DexCache::FixupStrings(GcRoot<mirror::String>* dest, const Visitor& visitor) { GcRoot<mirror::String>* src = GetStrings(); for (size_t i = 0, count = NumStrings(); i < count; ++i) { mirror::String* source = src[i].Read<kReadBarrierOption>(); mirror::String* new_source = visitor(source); dest[i] = GcRoot<mirror::String>(new_source); } } template <ReadBarrierOption kReadBarrierOption, typename Visitor> inline void DexCache::FixupResolvedTypes(GcRoot<mirror::Class>* dest, const Visitor& visitor) { GcRoot<mirror::Class>* src = GetResolvedTypes(); for (size_t i = 0, count = NumResolvedTypes(); i < count; ++i) { mirror::Class* source = src[i].Read<kReadBarrierOption>(); mirror::Class* new_source = visitor(source); dest[i] = GcRoot<mirror::Class>(new_source); } } } // namespace mirror } } } } // namespace facebook::museum::MUSEUM_VERSION::art #endif // ART_RUNTIME_MIRROR_DEX_CACHE_INL_H_
42.458333
98
0.727604
[ "object" ]
a517a2c5023e58328c9cc64404564486f5d562e1
7,958
h
C
components/zucchini/address_translator.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
components/zucchini/address_translator.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
components/zucchini/address_translator.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2017 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_ZUCCHINI_ADDRESS_TRANSLATOR_H_ #define COMPONENTS_ZUCCHINI_ADDRESS_TRANSLATOR_H_ #include <stdint.h> #include <tuple> #include <vector> #include "components/zucchini/algorithm.h" #include "components/zucchini/image_utils.h" namespace zucchini { // There are several ways to reason about addresses in an image: // - Offset: Position relative to start of image. // - VA (Virtual Address): Virtual memory address of a loaded image. This is // subject to relocation by the OS. // - RVA (Relative Virtual Address): VA relative to some base address. This is // the preferred way to specify pointers in an image. // // Zucchini is primarily concerned with offsets and RVAs. Executable images like // PE and ELF are organized into sections. Each section specifies offset and RVA // ranges as: // {Offset start, offset size, RVA start, RVA size}. // This constitutes a basic unit to translate between offsets and RVAs. Note: // |offset size| < |RVA size| is possible. For example, the .bss section can can // have zero-filled statically-allocated data that have no corresponding bytes // on image (to save space). This poses a problem for Zucchini, which stores // addresses as offsets: now we'd have "dangling RVAs" that don't map to // offsets! Some ways to handling this are: // 1. Ignore all dangling RVAs. This simplifies the algorithm, but also means // some reference targets would escape detection and processing. // 2. Create distinct "fake offsets" to accommodate dangling RVAs. Image data // must not be read on these fake offsets, which are only valid as target // addresses for reference matching. // As for |RVA size| < |offset size|, the extra portion just gets ignored. // // Status: Zucchini implements (2) in a simple way: dangling RVAs are mapped to // fake offsets by adding a large value. This value can be chosen as an // exclusive upper bound of all offsets (i.e., image size). This allows them to // be easily detected and processed as a special-case. // TODO(huangs): Investigate option (1), now that the refactored code makes // experimentation easier. // TODO(huangs): Make AddressTranslator smarter: Allocate unused |offset_t| // ranges and create "fake" units to accommodate dangling RVAs. Then // AddressTranslator can be simplified. // Virtual Address relative to some base address (RVA). There's distinction // between "valid RVA" and "existent RVA": // - Valid RVA: An RVA that's reasonably small, i.e., below |kRvaBound|. // - Existent RVA: An RVA that has semantic meaning in an image, and may // translate to an offset in an image or (if a dangling RVA) a fake offset. // All existent RVAs are valid RVAs. using rva_t = uint32_t; // Divide by 2 to match |kOffsetBound|. constexpr rva_t kRvaBound = static_cast<rva_t>(-1) / 2; constexpr rva_t kInvalidRva = static_cast<rva_t>(-2); // A utility to translate between offsets and RVAs in an image. class AddressTranslator { public: // A basic unit for address translation, roughly maps to a section, but may // be processed (e.g., merged) as an optimization. struct Unit { offset_t offset_end() const { return offset_begin + offset_size; } rva_t rva_end() const { return rva_begin + rva_size; } bool IsEmpty() const { // |rva_size == 0| and |offset_size > 0| means Unit hasn't been trimmed // yet, and once it is then it's empty. // |rva_size > 0| and |offset_size == 0| means Unit has dangling RVA, but // is not empty. return rva_size == 0; } bool CoversOffset(offset_t offset) const { return RangeCovers(offset_begin, offset_size, offset); } bool CoversRva(rva_t rva) const { return RangeCovers(rva_begin, rva_size, rva); } bool CoversDanglingRva(rva_t rva) const { return CoversRva(rva) && rva - rva_begin >= offset_size; } // Assumes valid |offset| (*cannot* be fake offset). rva_t OffsetToRvaUnsafe(offset_t offset) const { return offset - offset_begin + rva_begin; } // Assumes valid |rva| (*can* be danging RVA). offset_t RvaToOffsetUnsafe(rva_t rva, offset_t fake_offset_begin) const { rva_t delta = rva - rva_begin; return delta < offset_size ? delta + offset_begin : fake_offset_begin + rva; } bool HasDanglingRva() const { return rva_size > offset_size; } friend bool operator==(const Unit& a, const Unit& b) { return std::tie(a.offset_begin, a.offset_size, a.rva_begin, a.rva_size) == std::tie(b.offset_begin, b.offset_size, b.rva_begin, b.rva_size); } offset_t offset_begin; offset_t offset_size; rva_t rva_begin; rva_t rva_size; }; // An adaptor for AddressTranslator::OffsetToRva() that caches the last Unit // found, to reduce the number of OffsetToUnit() calls for clustered queries. class OffsetToRvaCache { public: // Embeds |translator| for use. Now object lifetime is tied to |translator| // lifetime. explicit OffsetToRvaCache(const AddressTranslator& translator); OffsetToRvaCache(const OffsetToRvaCache&) = delete; const OffsetToRvaCache& operator=(const OffsetToRvaCache&) = delete; rva_t Convert(offset_t offset) const; private: const AddressTranslator& translator_; mutable const AddressTranslator::Unit* cached_unit_ = nullptr; }; // An adaptor for AddressTranslator::RvaToOffset() that caches the last Unit // found, to reduce the number of RvaToUnit() calls for clustered queries. class RvaToOffsetCache { public: // Embeds |translator| for use. Now object lifetime is tied to |translator| // lifetime. explicit RvaToOffsetCache(const AddressTranslator& translator); RvaToOffsetCache(const RvaToOffsetCache&) = delete; const RvaToOffsetCache& operator=(const RvaToOffsetCache&) = delete; bool IsValid(rva_t rva) const; offset_t Convert(rva_t rva) const; private: const AddressTranslator& translator_; mutable const AddressTranslator::Unit* cached_unit_ = nullptr; }; enum Status { kSuccess = 0, kErrorOverflow, kErrorBadOverlap, kErrorBadOverlapDanglingRva, kErrorFakeOffsetBeginTooLarge, }; AddressTranslator(); AddressTranslator(AddressTranslator&&); AddressTranslator(const AddressTranslator&) = delete; const AddressTranslator& operator=(const AddressTranslator&) = delete; ~AddressTranslator(); // Consumes |units| to populate data in this class. Performs consistency // checks and overlapping Units. Returns Status to indicate success. Status Initialize(std::vector<Unit>&& units); // Returns the (possibly dangling) RVA corresponding to |offset|, or // kInvalidRva if not found. rva_t OffsetToRva(offset_t offset) const; // Returns the (possibly fake) offset corresponding to |rva|, or // kInvalidOffset if not found (i.e., |rva| is non-existent). offset_t RvaToOffset(rva_t rva) const; // For testing. offset_t fake_offset_begin() const { return fake_offset_begin_; } const std::vector<Unit>& units_sorted_by_offset() const { return units_sorted_by_offset_; } const std::vector<Unit>& units_sorted_by_rva() const { return units_sorted_by_rva_; } private: // Helper to find the Unit that contains given |offset| or |rva|. Returns null // if not found. const Unit* OffsetToUnit(offset_t offset) const; const Unit* RvaToUnit(rva_t rva) const; // Storage of Units. All offset ranges are non-empty and disjoint. Likewise // for all RVA ranges. std::vector<Unit> units_sorted_by_offset_; std::vector<Unit> units_sorted_by_rva_; // Conversion factor to translate between dangling RVAs and fake offsets. offset_t fake_offset_begin_; }; } // namespace zucchini #endif // COMPONENTS_ZUCCHINI_ADDRESS_TRANSLATOR_H_
39.79
80
0.723172
[ "object", "vector" ]
a51bbcf5fb55c8c9024e40661d6546732f41aa4b
5,137
h
C
research/carls/knowledge_bank/knowledge_bank.h
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
939
2019-08-28T06:50:30.000Z
2022-03-30T02:37:07.000Z
research/carls/knowledge_bank/knowledge_bank.h
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
80
2019-09-01T19:47:30.000Z
2022-02-02T20:38:38.000Z
research/carls/knowledge_bank/knowledge_bank.h
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
196
2019-09-01T19:38:53.000Z
2022-02-08T01:25:57.000Z
/*Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://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 NEURAL_STRUCTURED_LEARNING_RESEARCH_CARLS_KNOWLEDGE_BANK_KNOWLEDGE_BANK_H_ #define NEURAL_STRUCTURED_LEARNING_RESEARCH_CARLS_KNOWLEDGE_BANK_KNOWLEDGE_BANK_H_ #include "absl/container/flat_hash_map.h" #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "research/carls/base/proto_factory.h" #include "research/carls/embedding.pb.h" // proto to pb #include "research/carls/knowledge_bank/knowledge_bank_config.pb.h" // proto to pb namespace carls { // Macro for registering a knowledge bank implementation. #define REGISTER_KNOWLEDGE_BANK_FACTORY(proto_type, factory_type) \ REGISTER_CARLS_FACTORY_1(proto_type, factory_type, KnowledgeBankConfig, \ KnowledgeBank, int) // Base class for an KnowledgeBank. class KnowledgeBank { public: virtual ~KnowledgeBank(); // Looks up the embedding for a single key without updating the embedding. virtual absl::Status Lookup(const absl::string_view key, EmbeddingVectorProto* result) const = 0; // Looks up the embedding for a single key, and if the key is not found, // create a new embedding based on given initializer in KnowledgeBankConfig. virtual absl::Status LookupWithUpdate(const absl::string_view key, EmbeddingVectorProto* result) = 0; // Updates the embedding of a single key. // The function may move the value into the storage. virtual absl::Status Update(const absl::string_view key, const EmbeddingVectorProto& value) = 0; // Batch lookup for the given keys. // Returns a vector of variant [EmbeddingVectorProto, error message] with the // same length as the input keys. virtual void BatchLookup( const std::vector<absl::string_view>& keys, std::vector<absl::variant<EmbeddingVectorProto, std::string>>* value_or_errors) const; // Batch lookup with update for the given keys. // Returns a vector of variant [EmbeddingVectorProto, error message] with the // same length as the input keys. virtual void BatchLookupWithUpdate( const std::vector<absl::string_view>& keys, std::vector<absl::variant<EmbeddingVectorProto, std::string>>* value_or_errors); // Batch update. // Since the update is done one by one, it is not guaranteed that // atomic commit/cancellation if only part of the updates are successful. virtual std::vector<absl::Status> BatchUpdate( const std::vector<absl::string_view>& keys, const std::vector<EmbeddingVectorProto>& values); // Exports current data to a timestamped output directory with given subdir, // e.g., %export_directory%/%subdir% // The checkpoint contains the full file path of the saved binary proto of the // KnowledgeBankConfig upon success. absl::Status Export(const std::string& export_directory, const std::string& subdir, std::string* checkpoint); // Restores the stage of the embedding from the given saved path. absl::Status Import(const std::string& saved_path); // Returns embedding dimension. int embedding_dimension() const { return embedding_dimension_; } // Returns KnowledgeBankConfig. const KnowledgeBankConfig& config() { return config_; } // Returns the total number of keys in the knowledge store. virtual size_t Size() const = 0; // Returns the list of keys in the knowledge bank. virtual std::vector<absl::string_view> Keys() const = 0; // Check if a given key is already in the knowledge bank or not. // This is used for probing the bank without affecting weights of the // embedding. virtual bool Contains(absl::string_view key) const = 0; protected: KnowledgeBank(const KnowledgeBankConfig& config, const int embedding_dimension); // Internal implementation of the Export() method. // The caller is expected to export the files to %output_dir%/%subdir%. virtual absl::Status ExportInternal(const std::string& dir, std::string* exported_path) = 0; // Internal implementation of the Import() method. virtual absl::Status ImportInternal(const std::string& saved_path) = 0; KnowledgeBankConfig config_; const int embedding_dimension_; }; REGISTER_CARLS_BASE_CLASS_1(KnowledgeBankConfig, KnowledgeBank, KnowledgeBankFactory, int); } // namespace carls #endif // NEURAL_STRUCTURED_LEARNING_RESEARCH_CARLS_KNOWLEDGE_BANK_KNOWLEDGE_BANK_H_
41.427419
85
0.715398
[ "vector" ]
a52dd7c41ed7b86867c0d524ffd81bf95a54b342
25,053
c
C
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Applications/Display/LTDC_Paint/Src/main.c
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Applications/Display/LTDC_Paint/Src/main.c
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32756G_EVAL/Applications/Display/LTDC_Paint/Src/main.c
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * @file Display/LTDC_Paint/Src/main.c * @author MCD Application Team * @brief Main program body ****************************************************************************** * @attention * * Copyright (c) 2017 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "save.h" #include "color.h" #include "color2.h" /** @addtogroup STM32F7xx_HAL_Applications * @{ */ /** @addtogroup LTDC_Paint * @{ */ /* Private typedef -----------------------------------------------------------*/ typedef enum { APPLICATION_IDLE = 0, APPLICATION_RUNNIG }MSC_ApplicationTypeDef; /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ USBH_HandleTypeDef hUSB_Host; FATFS USBDISK_FatFs; /* File system object for USB Disk logical drive */ FIL MyFile; /* File object */ char USB_Path[4]; /* USB Disk logical drive path */ static uint32_t Radius = 2; static uint32_t x = 0, y = 0; static TS_StateTypeDef TS_State; const uint32_t aBMPHeader1[14]= {0x26E64D42, 0x0000000B, 0x00360000, 0x00280000, 0x02440000, 0x01A40000, 0x00010000, 0x00000018, 0xF5400000, 0x00000006, 0x00000000, 0x00000000, 0x00000000, 0x0000}; const uint32_t aBMPHeader2[14]= {0x13A64D42, 0x00000004, 0x00360000, 0x00280000, 0x01A40000, 0x00D40000, 0x00010000, 0x00000018, 0xF5400000, 0x00000006, 0x00000000, 0x00000000, 0x00000000, 0x0000}; /* Variable to save the state of USB */ MSC_ApplicationTypeDef Appli_state = APPLICATION_IDLE; /* Private function prototypes -----------------------------------------------*/ static void MPU_Config(void); static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id); static void Draw_Menu(void); static void GetPosition(void); static void SystemClock_Config(void); static void Error_Handler(void); static void Save_Picture(void); static void Prepare_Picture(void); static void Update_Color(void); static void Update_Size(uint8_t size); static void CPU_CACHE_Enable(void); /* Private functions ---------------------------------------------------------*/ /** * @brief Main program * @param None * @retval None */ int main(void) { /* Configure the MPU attributes */ MPU_Config(); /* Enable the CPU Cache */ CPU_CACHE_Enable(); /* STM32F7xx HAL library initialization: - Configure the Flash ART accelerator on ITCM interface - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); /* Configure the system clock to 200 MHz */ SystemClock_Config(); /* Configure LED1 and LED3 */ BSP_LED_Init(LED1); BSP_LED_Init(LED3); /*##-1- LCD Initialization #################################################*/ /* Initialize the LCD */ BSP_LCD_Init(); /* Foreground Layer Initialization */ BSP_LCD_LayerDefaultInit(1, LCD_FRAME_BUFFER_LAYER1); /* Set Foreground Layer */ BSP_LCD_SelectLayer(1); /* Clear the LCD Foreground layer */ BSP_LCD_Clear(LCD_COLOR_WHITE); /* Enable the color Key for foreground layer */ BSP_LCD_SetColorKeying(1, LCD_COLOR_WHITE); BSP_LCD_SetLayerVisible(1, DISABLE); /* Background Layer Initialization */ BSP_LCD_LayerDefaultInit(0, LCD_FRAME_BUFFER_LAYER0); /* Set Foreground Layer */ BSP_LCD_SelectLayer(0); /* Enable the LCD */ BSP_LCD_DisplayOn(); /* Clear the LCD Background layer */ BSP_LCD_Clear(LCD_COLOR_WHITE); /*##-2- Touch screen initialization ########################################*/ if(stmpe811_ts_drv.ReadID(TS_I2C_ADDRESS) == STMPE811_ID) { Touchscreen_Calibration(); } BSP_TS_Init(BSP_LCD_GetXSize(), BSP_LCD_GetYSize()); /*##-3- USB Initialization #################################################*/ /* Init Host Library */ if (USBH_Init(&hUSB_Host, USBH_UserProcess, 0) != USBH_OK) { /* USB Initialization Error */ Error_Handler(); } /* Add Supported Class */ USBH_RegisterClass(&hUSB_Host, USBH_MSC_CLASS); /* Start Host Process */ if (USBH_Start(&hUSB_Host) != USBH_OK) { /* USB Initialization Error */ Error_Handler(); } /*##-4- Link the USB Mass Storage disk I/O driver ##########################*/ if(FATFS_LinkDriver(&USBH_Driver, USB_Path) != 0) { /* FatFs Initialization Error */ Error_Handler(); } /*##-5- Register the file system object to the FatFs module ################*/ if(f_mount(&USBDISK_FatFs, (TCHAR const*)USB_Path, 0) != FR_OK) { /* FatFs Initialization Error */ Error_Handler(); } /*##-6- Draw the menu ######################################################*/ Draw_Menu(); /* Infinite loop */ while (1) { /*##-7- Configure the touch screen and Get the position ##################*/ GetPosition(); USBH_Process(&hUSB_Host); } } /** * @brief User Process * @param None * @retval None */ static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id) { switch (id) { case HOST_USER_DISCONNECTION: Appli_state = APPLICATION_IDLE; if (f_mount(&USBDISK_FatFs, "", 0) != FR_OK) { /* FatFs Initialization Error */ Error_Handler(); } break; case HOST_USER_CLASS_ACTIVE: Appli_state = APPLICATION_RUNNIG; break; } } /** * @brief Configures and gets Touch screen position. * @param None * @retval None */ static void GetPosition(void) { static uint32_t color_width; static uint32_t color; if (BSP_LCD_GetXSize() == 640) { color_width = 36; } else { color_width = 19; } /* Get Touch screen position */ BSP_TS_GetState(&TS_State); /* Read the coordinate */ if(stmpe811_ts_drv.ReadID(TS_I2C_ADDRESS) == STMPE811_ID) { x = Calibration_GetX(TS_State.x); y = Calibration_GetX(TS_State.y); } else { x = TS_State.x; y = TS_State.y; } if ((TS_State.TouchDetected) & (x > (67 + Radius)) & (y > (7 + Radius) ) & ( x < (BSP_LCD_GetXSize()-(7 + Radius )) ) & (y < (BSP_LCD_GetYSize()-(67 + Radius )) )) { BSP_LCD_FillCircle((x), (y), Radius); } else if ((TS_State.TouchDetected) & (x > 0 ) & ( x < 50 )) { if ((TS_State.TouchDetected) & ( y > 0 ) & ( y < color_width )) { BSP_LCD_SetTextColor(LCD_COLOR_WHITE); Update_Size(Radius); } else if ((TS_State.TouchDetected) & ( y > color_width ) & (y < (2 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_YELLOW); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (2 * color_width)) & (y < (3 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_ORANGE); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (3 * color_width)) & (y < (4 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_LIGHTMAGENTA); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (4 * color_width)) & (y < (5 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_DARKGREEN); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (5 * color_width)) &(y < (6 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_GREEN); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (6 * color_width)) &(y < (7 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_BROWN); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (7 * color_width)) & (y < (8 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_RED); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (8 * color_width)) & (y < (9 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_DARKMAGENTA); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (9 * color_width)) & (y < (10 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_CYAN); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (10 * color_width)) & (y < (11 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_DARKBLUE); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (11 * color_width)) & (y < (12 * color_width))) { BSP_LCD_SetTextColor(LCD_COLOR_BLACK); Update_Size(Radius); } else if ((TS_State.TouchDetected) & (y > (12 * color_width)) & (y < (13 * color_width))) { /* Get the current text color */ color = BSP_LCD_GetTextColor(); BSP_LCD_SetTextColor(LCD_COLOR_WHITE); /* Clear the working window */ BSP_LCD_FillRect(68, 8, (BSP_LCD_GetXSize() - 75), (BSP_LCD_GetYSize() - 75)); BSP_LCD_SetTextColor(color); } else { x = 0; y = 0; } Update_Color(); } else if ((TS_State.TouchDetected) & (x > 70 ) & (y > (12 * color_width)) & (y < (13 * color_width)) & ( x < 120 )) { Radius = 20; Update_Size(Radius); } else if ((TS_State.TouchDetected) & (x > 120 ) & (y > (12 * color_width)) & (y < (13 * color_width)) & ( x < 170 )) { Radius = 15; Update_Size(Radius); } else if ((TS_State.TouchDetected) & (x > 170 ) & (y > (12 * color_width)) & (y < (13 * color_width)) & ( x < 220 )) { Radius = 10; Update_Size(Radius); } else if ((TS_State.TouchDetected) & (x > 220 ) & (y > (12 * color_width)) & (y < (13 * color_width)) & ( x < 270 )) { Radius = 5; Update_Size(Radius); } else if ((TS_State.TouchDetected) & (x > 270 ) & (y > (12 * color_width)) & (y < (13 * color_width)) & ( x < 320 )) { Radius = 2; Update_Size(Radius); } else if ((TS_State.TouchDetected) & (((x > (BSP_LCD_GetXSize()-5) ) & (y > (12 * color_width)) & (y < (13 * color_width))) | (( x < 55 ) & ( y < 5 )))) { TS_State.x = 0; TS_State.y = 0; } else if ((TS_State.TouchDetected) & (x > 320) & (y > (BSP_LCD_GetYSize() - 50)) & (x < 370) & (y < BSP_LCD_GetYSize() )) { Save_Picture(); } } /** * @brief Draws the menu. * @param None * @retval None */ static void Draw_Menu(void) { /* Set background Layer */ BSP_LCD_SelectLayer(0); /* Clear the LCD */ BSP_LCD_Clear(LCD_COLOR_WHITE); if (BSP_LCD_GetXSize() == 640) { /* Draw color image */ BSP_LCD_DrawBitmap(0, 0, (uint8_t *)color); } else { /* Draw color image */ BSP_LCD_DrawBitmap(0, 0, (uint8_t *)color2); } /* Draw save image */ BSP_LCD_DrawBitmap(310, (BSP_LCD_GetYSize() - 50), (uint8_t *)save); /* Set Black as text color */ BSP_LCD_SetTextColor(LCD_COLOR_BLACK); /* Draw working window */ BSP_LCD_DrawRect(61, 0, (BSP_LCD_GetXSize() - 61), (BSP_LCD_GetYSize() - 60)); BSP_LCD_DrawRect(63, 3, (BSP_LCD_GetXSize() - 66), (BSP_LCD_GetYSize() - 66)); BSP_LCD_DrawRect(65, 5, (BSP_LCD_GetXSize() - 70), (BSP_LCD_GetYSize() - 70)); BSP_LCD_DrawRect(67, 7, (BSP_LCD_GetXSize() - 74), (BSP_LCD_GetYSize() - 74)); /* Draw size icons */ BSP_LCD_FillRect(60, (BSP_LCD_GetYSize() - 48), 250, 48); BSP_LCD_SetTextColor(LCD_COLOR_WHITE); BSP_LCD_FillCircle(95, (BSP_LCD_GetYSize() - 24), 20); BSP_LCD_FillCircle(145, (BSP_LCD_GetYSize() - 24), 15); BSP_LCD_FillCircle(195, (BSP_LCD_GetYSize() - 24), 10); BSP_LCD_FillCircle(245, (BSP_LCD_GetYSize() - 24), 5); BSP_LCD_FillCircle(295, (BSP_LCD_GetYSize() - 24), 2); BSP_LCD_SetTextColor(LCD_COLOR_DARKRED); BSP_LCD_SetFont(&Font8); BSP_LCD_DisplayStringAt(360, (BSP_LCD_GetYSize() - 55), (uint8_t *)"Selected Color Size", LEFT_MODE); BSP_LCD_SetTextColor(LCD_COLOR_BLACK); BSP_LCD_FillRect(380, (BSP_LCD_GetYSize() - 40), 30, 30); BSP_LCD_FillCircle(450, (BSP_LCD_GetYSize()- 24), Radius); } /** * @brief Save the picture in USB Disk. * @param None * @retval None */ void Save_Picture(void) { FRESULT res1, res2; /* FatFs function common result code */ uint32_t byteswritten; /* File write count */ BSP_LCD_SetLayerVisible(1, ENABLE); BSP_LCD_SetColorKeying(1, LCD_COLOR_WHITE); /* Set foreground Layer */ BSP_LCD_SelectLayer(1); BSP_LCD_SetTextColor(LCD_COLOR_DARKRED); BSP_LCD_SetFont(&Font20); /* Turn LED1 and LED3 Off */ BSP_LED_Off(LED1); BSP_LED_Off(LED3); if (Appli_state == APPLICATION_RUNNIG) { BSP_LCD_DisplayStringAt(10, (BSP_LCD_GetYSize()-100), (uint8_t *)"Saving ... ", RIGHT_MODE); /*##-1- Prepare the image to be saved ####################################*/ Prepare_Picture(); /*##-2- Create and Open a new bmp file object with write access ##########*/ if(f_open(&MyFile, "image.bmp", FA_CREATE_ALWAYS | FA_WRITE) != FR_OK) { /* 'image.bmp' file Open for write Error */ Error_Handler(); } else { /*##-3- Write data to the BMP file #####################################*/ /* Write the BMP header */ if (BSP_LCD_GetXSize() == 640) { /* if ampire 640x480 LCD is used */ res1 = f_write(&MyFile, (uint32_t *)aBMPHeader1, 54, (void *)&byteswritten); } else { /* if ampire 480x272 LCD is used */ res1 = f_write(&MyFile, (uint32_t *)aBMPHeader2, 54, (void *)&byteswritten); } /* Write the bmp file */ res2 = f_write(&MyFile, (uint32_t *)CONVERTED_FRAME_BUFFER, ((BSP_LCD_GetYSize()-60)*(BSP_LCD_GetXSize()-60)*3), (void *)&byteswritten); if((res1 != FR_OK) || (res2 != FR_OK) || (byteswritten == 0)) { /* 'image' file Write or EOF Error */ BSP_LED_On(LED3); BSP_LCD_DisplayStringAt(10, (BSP_LCD_GetYSize()-100), (uint8_t *)" Aborted...", RIGHT_MODE); /* Wait for 2s */ HAL_Delay(2000); /* Disable the Layer 2 */ BSP_LCD_SetLayerVisible(1, DISABLE); /* Select Layer 1 */ BSP_LCD_SelectLayer(0); } else { /*##-4- Close the open text file #####################################*/ f_close(&MyFile); /* Success of the demo: no error occurrence */ BSP_LED_On(LED1); BSP_LCD_SetTextColor(LCD_COLOR_DARKGREEN); BSP_LCD_DisplayStringAt(10, (BSP_LCD_GetYSize()-100), (uint8_t *)" Saved ", RIGHT_MODE); /* Wait for 2s */ HAL_Delay(2000); /* Disable the Layer 2 */ BSP_LCD_SetLayerVisible(1, DISABLE); /* Select Layer 1 */ BSP_LCD_SelectLayer(0); } } } else { /* USB not connected */ BSP_LCD_DisplayStringAt(10, (BSP_LCD_GetYSize()-100), (uint8_t *)"USB KO... ", RIGHT_MODE); /* Wait for 2s */ HAL_Delay(2000); /* Disable the Layer 2 */ BSP_LCD_SetLayerVisible(1, DISABLE); /* Select Layer 1 */ BSP_LCD_SelectLayer(0); } } /** * @brief Prepares the picture to be Saved in USB Disk. * @param None * @retval None */ static void Prepare_Picture(void) { static DMA2D_HandleTypeDef hdma2d_eval; uint32_t address1 = CONVERTED_FRAME_BUFFER; uint32_t address2 = LCD_FRAME_BUFFER_LAYER0; uint32_t index = 0; /* Configure the DMA2D Mode, Color Mode and output offset */ hdma2d_eval.Init.Mode = DMA2D_M2M_PFC; hdma2d_eval.Init.ColorMode = DMA2D_OUTPUT_RGB888; hdma2d_eval.Init.OutputOffset = 0; /* Foreground Configuration */ hdma2d_eval.LayerCfg[1].AlphaMode = DMA2D_NO_MODIF_ALPHA; hdma2d_eval.LayerCfg[1].InputAlpha = 0xFF; hdma2d_eval.LayerCfg[1].InputColorMode = DMA2D_INPUT_ARGB8888; hdma2d_eval.LayerCfg[1].InputOffset = 60; hdma2d_eval.Instance = DMA2D; /* Bypass the bitmap header */ address2 += ((BSP_LCD_GetXSize() * (BSP_LCD_GetYSize() - 61) + 60) * 4); /* Convert picture to RGB888 pixel format */ for(index=0; index < (BSP_LCD_GetYSize() - 60); index++) { /* DMA2D Initialization */ if(HAL_DMA2D_Init(&hdma2d_eval) == HAL_OK) { if(HAL_DMA2D_ConfigLayer(&hdma2d_eval, 1) == HAL_OK) { if (HAL_DMA2D_Start(&hdma2d_eval, address2, address1, (BSP_LCD_GetXSize() - 60), 1) == HAL_OK) { /* Polling For DMA transfer */ HAL_DMA2D_PollForTransfer(&hdma2d_eval, 10); } } } /* Increment the source and destination buffers */ address1 += ((BSP_LCD_GetXSize() - 60)*3); address2 -= BSP_LCD_GetXSize()*4; } } /** * @brief Clock Config. * @param hltdc: LTDC handle * @note This API is called by BSP_LCD_Init() * @retval None */ void BSP_LCD_ClockConfig(LTDC_HandleTypeDef *hltdc, void *Params) { static RCC_PeriphCLKInitTypeDef periph_clk_init_struct; if(stmpe811_ts_drv.ReadID(TS_I2C_ADDRESS) == STMPE811_ID) { /* AMPIRE480272 LCD clock configuration */ /* PLLSAI_VCO Input = HSE_VALUE/PLL_M = 1 Mhz */ /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN = 192 Mhz */ /* PLLLCDCLK = PLLSAI_VCO Output/PLLSAIR = 192/5 = 38.4 Mhz */ /* LTDC clock frequency = PLLLCDCLK / LTDC_PLLSAI_DIVR_4 = 38.4/4 = 9.6Mhz */ periph_clk_init_struct.PeriphClockSelection = RCC_PERIPHCLK_LTDC; periph_clk_init_struct.PLLSAI.PLLSAIN = 192; periph_clk_init_struct.PLLSAI.PLLSAIR = AMPIRE480272_FREQUENCY_DIVIDER; periph_clk_init_struct.PLLSAIDivR = RCC_PLLSAIDIVR_4; HAL_RCCEx_PeriphCLKConfig(&periph_clk_init_struct); } else { /* AMPIRE640480 LCD clock configuration */ /* PLLSAI_VCO Input = HSE_VALUE/PLL_M = 1 Mhz */ /* PLLSAI_VCO Output = PLLSAI_VCO Input * PLLSAIN = 192 Mhz */ /* PLLLCDCLK = PLLSAI_VCO Output/PLLSAIR = 192/5 = 38.4 Mhz */ /* LTDC clock frequency = PLLLCDCLK / LTDC_PLLSAI_DIVR_2 = 38.4/2 = 19.2 Mhz */ periph_clk_init_struct.PeriphClockSelection = RCC_PERIPHCLK_LTDC; periph_clk_init_struct.PLLSAI.PLLSAIN = 192; periph_clk_init_struct.PLLSAI.PLLSAIR = 5; periph_clk_init_struct.PLLSAIDivR = RCC_PLLSAIDIVR_2; HAL_RCCEx_PeriphCLKConfig(&periph_clk_init_struct); } } /** * @brief This function is executed in case of error occurrence. * @param None * @retval None */ static void Error_Handler(void) { /* Turn LED3 on */ BSP_LED_On(LED3); while(1) { } } /** * @brief Update the selected color * @param None * @retval None */ static void Update_Color(void) { static uint32_t color; /* Get the current text color */ color = BSP_LCD_GetTextColor(); /* Update the selected color icon */ BSP_LCD_FillRect(380, (BSP_LCD_GetYSize()-40), 30, 30); BSP_LCD_SetTextColor(LCD_COLOR_BLACK); BSP_LCD_DrawRect(380, (BSP_LCD_GetYSize()-40), 30, 30); BSP_LCD_SetTextColor(color); } /** * @brief Updates the selected size * @param size: Size to be updated * @retval None */ static void Update_Size(uint8_t size) { static uint32_t color; /* Get the current text color */ color = BSP_LCD_GetTextColor(); /* Update the selected size icon */ BSP_LCD_SetTextColor(LCD_COLOR_WHITE); BSP_LCD_FillCircle(450, (BSP_LCD_GetYSize()-24), 20); BSP_LCD_SetTextColor(color); BSP_LCD_FillCircle(450, (BSP_LCD_GetYSize()-24), size); BSP_LCD_SetTextColor(LCD_COLOR_BLACK); BSP_LCD_DrawCircle(450, (BSP_LCD_GetYSize()-24), size); BSP_LCD_SetTextColor(color); } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSE) * SYSCLK(Hz) = 200000000 * HCLK(Hz) = 200000000 * AHB Prescaler = 1 * APB1 Prescaler = 4 * APB2 Prescaler = 2 * HSE Frequency(Hz) = 25000000 * PLL_M = 25 * PLL_N = 400 * PLL_P = 2 * PLL_Q = 8 * VDD(V) = 3.3 * Main regulator output voltage = Scale1 mode * Flash Latency(WS) = 6 * @param None * @retval None */ static void SystemClock_Config(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; HAL_StatusTypeDef ret = HAL_OK; /* Enable HSE Oscillator and activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLM = 25; RCC_OscInitStruct.PLL.PLLN = 400; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; RCC_OscInitStruct.PLL.PLLQ = 8; ret = HAL_RCC_OscConfig(&RCC_OscInitStruct); if(ret != HAL_OK) { while(1) { ; } } /* Activate the OverDrive to reach the 216 MHz Frequency */ ret = HAL_PWREx_EnableOverDrive(); if(ret != HAL_OK) { while(1) { ; } } /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; ret = HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_6); if(ret != HAL_OK) { while(1) { ; } } } /** * @brief CPU L1-Cache enable. * @param None * @retval None */ static void CPU_CACHE_Enable(void) { /* Enable I-Cache */ SCB_EnableICache(); /* Enable D-Cache */ SCB_EnableDCache(); } /** * @brief Configure the MPU attributes * @param None * @retval None */ static void MPU_Config(void) { MPU_Region_InitTypeDef MPU_InitStruct; /* Disable the MPU */ HAL_MPU_Disable(); /* Configure the MPU as Strongly ordered for not defined regions */ MPU_InitStruct.Enable = MPU_REGION_ENABLE; MPU_InitStruct.BaseAddress = 0x00; MPU_InitStruct.Size = MPU_REGION_SIZE_4GB; MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS; MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE; MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE; MPU_InitStruct.Number = MPU_REGION_NUMBER0; MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; MPU_InitStruct.SubRegionDisable = 0x87; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); /* Configure the MPU attributes as WT for SDRAM */ MPU_InitStruct.Enable = MPU_REGION_ENABLE; MPU_InitStruct.BaseAddress = 0xC0000000; MPU_InitStruct.Size = MPU_REGION_SIZE_32MB; MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE; MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE; MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE; MPU_InitStruct.Number = MPU_REGION_NUMBER1; MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; MPU_InitStruct.SubRegionDisable = 0x00; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); /* Configure the MPU attributes FMC control registers */ MPU_InitStruct.Enable = MPU_REGION_ENABLE; MPU_InitStruct.BaseAddress = 0xA0000000; MPU_InitStruct.Size = MPU_REGION_SIZE_8KB; MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE; MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE; MPU_InitStruct.Number = MPU_REGION_NUMBER2; MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; MPU_InitStruct.SubRegionDisable = 0x0; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); /* Enable the MPU */ HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT); } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t* file, uint32_t line) { /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* Infinite loop */ while (1) { } } #endif /** * @} */ /** * @} */
30.777641
166
0.624117
[ "object" ]
a533d272ac1aa860e500aee0c8247e1980c0ec7e
2,506
h
C
third-party/slapi/win/headers/LayOutAPI/model/layerlist.h
kant/Sketchup-API-C-Wrapper
807f450fc80d4111ac3a4f057013f300bca07bff
[ "MIT" ]
20
2017-04-05T07:29:44.000Z
2022-01-10T18:41:42.000Z
third-party/slapi/win/headers/LayOutAPI/model/layerlist.h
kant/Sketchup-API-C-Wrapper
807f450fc80d4111ac3a4f057013f300bca07bff
[ "MIT" ]
42
2017-05-21T07:47:14.000Z
2019-10-31T16:19:00.000Z
third-party/slapi/win/headers/LayOutAPI/model/layerlist.h
kant/Sketchup-API-C-Wrapper
807f450fc80d4111ac3a4f057013f300bca07bff
[ "MIT" ]
9
2017-04-20T13:03:13.000Z
2022-02-08T23:53:36.000Z
// Copyright 2015 Trimble Navigation Ltd. All rights reserved. // This file is intended for public distribution. #ifndef LAYOUT_MODEL_LAYER_LIST_H_ #define LAYOUT_MODEL_LAYER_LIST_H_ #include <LayOutAPI/common.h> #include <LayOutAPI/model/defs.h> /** @struct LOLayerListRef @brief References an ordered, indexable list of \ref LOLayerRef objects. */ #ifdef __cplusplus extern "C" { #endif // __cplusplus /** @brief Creates a new empty layer list object. @param[out] layer_list The layer definition list object. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_NULL_POINTER_OUTPUT if layer_list is NULL - \ref SU_ERROR_OVERWRITE_VALID if *layer_list already refers to a valid object */ LO_RESULT LOLayerListCreate(LOLayerListRef* layer_list); /** @brief Releases a layer list object. *layer_list will be set to invalid by this function. @param[in] layer_list The layer definition list object. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_NULL_POINTER_INPUT if layer_list is NULL - \ref SU_ERROR_INVALID_INPUT if *layer_list does not refer to a valid object */ LO_RESULT LOLayerListRelease(LOLayerListRef* layer_list); /** @brief Gets the number of layer definitions in the list. @param[in] layer_list The layer definition list object. @param[out] num_layers The number of layer definitions in the list. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if layer_list does not refer to a valid object - \ref SU_ERROR_NULL_POINTER_OUTPUT if num_layers is NULL */ LO_RESULT LOLayerListGetNumberOfLayers(LOLayerListRef layer_list, size_t* num_layers); /** @brief Gets the layer definition at the specified index. @param[in] layer_list The layer definition list object. @param[in] index The index of the layer definition object to get. @param[out] layer The layer definition object. @return - \ref SU_ERROR_NONE on success - \ref SU_ERROR_INVALID_INPUT if layer_list does not refer to a valid object - \ref SU_ERROR_OUT_OF_RANGE if index is out of range for this list - \ref SU_ERROR_NULL_POINTER_OUTPUT if layer is NULL - \ref SU_ERROR_OVERWRITE_VALID if *layer already refers to a valid object */ LO_RESULT LOLayerListGetLayerAtIndex(LOLayerListRef layer_list, size_t index, LOLayerRef* layer); #ifdef __cplusplus } // end extern "C" #endif // __cplusplus #endif // LAYOUT_MODEL_LAYER_LIST_H_
34.805556
80
0.742618
[ "object", "model" ]
a53b0df19e0ce350e3b8c1635edad2f923e338b9
4,960
h
C
src/unit_CASCADE/ChIrrCascadeMeshTools.h
scpeters/chrono
a7cefda35d8a445963297cbe2dbb3cdfb4397f16
[ "BSD-3-Clause" ]
1
2020-02-16T16:52:08.000Z
2020-02-16T16:52:08.000Z
src/unit_CASCADE/ChIrrCascadeMeshTools.h
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
src/unit_CASCADE/ChIrrCascadeMeshTools.h
Milad-Rakhsha/Project-Chrono
6ab7abcd532cfb3c5e3876478fdd49c7ab783f63
[ "BSD-3-Clause" ]
null
null
null
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2011-2012 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #ifndef CHIRRCASCADEMESHTOOLS_H #define CHIRRCASCADEMESHTOOLS_H ////////////////////////////////////////////////// // // ChIrrCascadeMeshTools.h // // FOR IRRLICHT USERS ONLY! // // Some functions to allow easy creation of // meshes for Irrlicht visualization from OpenCASCADE shapes // // HEADER file for CHRONO, // Multibody dynamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include <irrlicht.h> #include "ChCascadeDoc.h" #include "ChCascadeMeshTools.h" #include <TopoDS_Shape.hxx> #include <TopoDS.hxx> #include <TopoDS_HShape.hxx> #include <Handle_TopoDS_TShape.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <TopoDS_Compound.hxx> #include <BRep_Builder.hxx> #include <BRepTools.hxx> #include <BRep_Tool.hxx> #include <BRepMesh.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeVertex.hxx> #include <TopExp_Explorer.hxx> #include <TopLoc_Location.hxx> #include <TopoDS_Iterator.hxx> #include <BRepAdaptor_HSurface.hxx> #include <Poly_Connect.hxx> #include <Poly_Triangle.hxx> #include <Poly_Triangulation.hxx> #include <TColgp_Array1OfDir.hxx> namespace irr { namespace scene { /// Tools to convert an OpenCASCADE shapes into /// 'Irrlicht' triangle meshes. class ChIrrCascadeMeshTools { public: //--------------------------------------------------------------------------------- // CONVERSION TO 'IRRLICHT' MESHES /// Function to use to convert a OpenCASCADE face into a Irrlicht mesh, /// so that it can be used for visualizing it. static void fillIrrlichtMeshFromCascadeFace(scene::IMesh* pMesh, const TopoDS_Face& F, video::SColor clr = video::SColor(255, 255,255,255)) { BRepAdaptor_Surface BS(F, Standard_False); Handle(BRepAdaptor_HSurface) gFace = new BRepAdaptor_HSurface(BS); GeomAbs_SurfaceType thetype = BS.GetType(); if (thetype == GeomAbs_Cylinder) {;}; Handle(Poly_Triangulation) T; TopLoc_Location theLocation; T = BRep_Tool::Triangulation(F, theLocation); int vertface=0; int vertshift=1; if (!T.IsNull()) { Poly_Connect pc(T); irr::scene::SMeshBuffer* buffer = new irr::scene::SMeshBuffer(); buffer->Vertices.set_used( T->NbNodes() ); buffer->Indices.set_used ( T->NbTriangles()*3); const TColgp_Array1OfPnt& mNodes = T->Nodes(); TColgp_Array1OfDir mNormals(mNodes.Lower(), mNodes.Upper()); // to compute the normal. chrono::cascade::ChCascadeMeshTools::ComputeNormal(F, pc, mNormals); int ivert = 0; for (int j= mNodes.Lower(); j<= mNodes.Upper(); j++) { gp_Pnt p; gp_Dir pn; p = mNodes(j).Transformed(theLocation.Transformation()); pn = mNormals(j); chrono::ChVector<> pos( p.X(),p.Y(),p.Z() ); chrono::ChVector<> nor( pn.X(),pn.Y(),pn.Z() ); buffer->Vertices[ivert] = irr::video::S3DVertex((irr::f32)pos.x, (irr::f32)pos.y, (irr::f32)pos.z, (irr::f32)nor.x, (irr::f32)nor.y, (irr::f32)nor.z, clr, 0, 0); ivert++; } int itri =0; for (int j= T->Triangles().Lower(); j<= T->Triangles().Upper(); j++) { Standard_Integer n[3]; if (F.Orientation() == TopAbs_REVERSED) T->Triangles()(j).Get(n[0],n[2],n[1]); else T->Triangles()(j).Get(n[0],n[1],n[2]); int ia = (n[0])-1; int ib = (n[1])-1; int ic = (n[2])-1; buffer->Indices[itri*3+0]=ia; buffer->Indices[itri*3+1]=ib; buffer->Indices[itri*3+2]=ic; itri++; } irr::scene::SMesh* mmesh = dynamic_cast<irr::scene::SMesh*>(pMesh); mmesh->addMeshBuffer(buffer); mmesh->recalculateBoundingBox(); } } /// Function to use to convert a OpenCASCADE shape into a Irrlicht mesh, /// so that it can be used for visualizing it. static void fillIrrlichtMeshFromCascade (scene::IMesh* pMesh, const TopoDS_Shape& mshape, double deflection=0.5, double angulardeflection=20, video::SColor clr = video::SColor(255, 255,255,255)) { BRepTools::Clean(mshape); BRepMesh::Mesh(mshape, deflection); // BRepMesh_IncrementalMesh M(mshape, deflection, Standard_False , angulardeflection); //GetLog() << " ..tesselation done \n"; // Loop on faces.. TopExp_Explorer ex; for (ex.Init(mshape, TopAbs_FACE); ex.More(); ex.Next()) { const TopoDS_Face& F = TopoDS::Face(ex.Current()); fillIrrlichtMeshFromCascadeFace(pMesh, F, clr); } } }; } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ #endif // END of header
26.524064
102
0.629637
[ "mesh", "shape" ]
a54951ba2dc25fd3e7e45833180c19fbfee1ba1c
5,716
h
C
whisperstreamlib/flv/flv_joiner.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/flv/flv_joiner.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
whisperstreamlib/flv/flv_joiner.h
cpopescu/whispercast
dd4ee1d4fa2e3436fc2387240eb3f5622749d944
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2009, Whispersoft s.r.l. // 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 Whispersoft s.r.l. 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. // // Authors: Catalin Popescu #ifndef __MEDIA_FLV_FLV_JOINER_H__ #define __MEDIA_FLV_FLV_JOINER_H__ #include <string> #include <vector> #include <whisperlib/common/base/types.h> #include <whisperstreamlib/base/joiner.h> #include <whisperstreamlib/flv/flv_tag.h> #include <whisperstreamlib/flv/flv_file_writer.h> namespace streaming { ////////////////////////////////////////////////////////////////////// // Use this to join flv files: // Object that holds the state and logic for join proceessing. class FlvJoinProcessor : public streaming::JoinProcessor { private: struct CuePoint { uint32 timestamp_; uint32 position_; CuePoint(uint32 timestamp, uint32 position) : timestamp_(timestamp), position_(position) {} }; public: // cue_ms_time: milliseconds between consecutive cue points FlvJoinProcessor(uint32 cue_ms); virtual ~FlvJoinProcessor(); // Call this after constructor to initialize the save state. virtual bool Initialize(const string& out_file); // Call this before starting to read a new file virtual void MarkNewFile(); // After processing everything, call this to finalize the output file // with cue-points and stuff.. // returns: >0 : file duration in milliseconds // -1 : error virtual int64 FinalizeFile(); // Main tag processor virtual PROCESS_STATUS ProcessTag(const streaming::Tag* media_tag, int64 timestamp_ms); private: // Helper - writes a cue point to writer_ void WriteCuePoint(int crt_cue, double position, int64 timestamp_ms); // Helper to process a metadata tag. // Checks if this metadata is compatible with the first one. // Params: // skip_file: true -> incompatibility found, abort processing current file // false -> continue processing current file // Returns: true -> write metadata in output file // false -> skip this metadata bool ProcessMetaData(const streaming::FlvTag::Metadata& medata, bool* skip_file); // Utilities for cue-point preparation static void PrepareCuePoint(int index, double position, int64 timestamp_ms, rtmp::CMixedMap* out); static void PrepareCuePoints(const vector<CuePoint>& cues, rtmp::CMixedMap* out); static void PrepareMetadataValues(double file_duration, int64 file_size, const vector<CuePoint>& cues, rtmp::CMixedMap* out); private: // we use this as temporarily output string out_file_tmp_; // final output file string out_file_; // simple writer FlvFileWriter writer_; // milliseconds between consecutive cuepoints const uint32 cue_ms_; // the metadata saved from the 1st file rtmp::CMixedMap metadata_; // These flags are needed for the output file header (the header & metadata // specify if the file contains audio/video). bool has_video_; bool has_audio_; // count audio/video tag. uint64 video_tag_count_; uint64 audio_tag_count_; // monotonic timestamps // for incoming tags (from various input file) int64 last_in_timestamp_ms_; // for outgoing tags (to output file) int64 last_out_timestamp_ms_; int64 next_cue_timestamp_ms_; vector<CuePoint> cues_; DISALLOW_EVIL_CONSTRUCTORS(FlvJoinProcessor); }; // Joins multiple files into a single big flv file. // The input file format The output file will // contain cuePoints to enable seek. // return: the duration of the output file in milliseconds, // or -1 on failure. // It return 0 is the files contain only metadata. int64 JoinFilesIntoFlv(const vector<string>& in_files, const string& out_file, uint32 cue_ms_time); // Same JoinFiles but with only 1 input file -> 1 output file.. // The reason for 1 file -> 1 file transformation is that // the output file contains cuePoints thus becoming seekable. int64 JoinFilesIntoFlv(const string& in_file, const string& out_file, uint32 cue_ms_time); } #endif // __MEDIA_FLV_FLV_JOINER_H__
36.877419
77
0.704864
[ "object", "vector" ]
a5496da7cd0c474afe0184e1427fada518478012
9,079
c
C
ApproxSpline/Resources/C-Sources/dierckx/ex/mnpasu.c
modelica-3rdparty/ApproxSpline
28420f5c1a88c9cd069defbd8c05e4a78a090675
[ "BSD-3-Clause" ]
2
2020-07-13T17:24:35.000Z
2021-03-18T16:16:02.000Z
ApproxSpline/Resources/C-Sources/dierckx/ex/mnpasu.c
tbeu/ApproxSpline
28420f5c1a88c9cd069defbd8c05e4a78a090675
[ "BSD-3-Clause" ]
2
2019-03-28T09:08:23.000Z
2022-03-29T07:35:48.000Z
ApproxSpline/Resources/C-Sources/dierckx/ex/mnpasu.c
modelica-3rdparty/ApproxSpline
28420f5c1a88c9cd069defbd8c05e4a78a090675
[ "BSD-3-Clause" ]
3
2018-10-21T07:46:49.000Z
2022-03-29T20:02:06.000Z
/* mnpasu.f -- translated by f2c (version 19961017). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* Table of constant values */ static integer c__1 = 1; static integer c__693 = 693; static integer c__128 = 128; static integer c__32 = 32; /* ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc */ /* c cc */ /* c mnpasu : parsur test program cc */ /* c cc */ /* ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc */ /* Main program */ MAIN__(void) { /* Format strings */ static char fmt_900[] = "(\0021the input data\002)"; static char fmt_905[] = "(\0020\002,2x,\002v\002,11(3x,f4.1))"; static char fmt_910[] = "(\002 \002,1x,\002u\002)"; static char fmt_915[] = "(\002 \002,f4.1)"; static char fmt_920[] = "(11f7.3)"; static char fmt_925[] = "(5x,11f7.3)"; static char fmt_935[] = "(\0020least-squares surface of periodicity\002,2i3)"; static char fmt_940[] = "(\0020smoothing surface of periodicity\002,2i3)"; static char fmt_945[] = "(\002 smoothing factor s=\002,f8.2)"; static char fmt_950[] = "(1x,\002sum squared residuals =\002,e15.6,5x,\002error flag=\002,i3)"; static char fmt_955[] = "(1x,\002total number of knots in the u-direction =\002,i3)"; static char fmt_960[] = "(1x,\002position of the knots \002)"; static char fmt_965[] = "(5x,10f6.2)"; static char fmt_970[] = "(1x,\002total number of knots in the v-direction =\002,i3)"; static char fmt_975[] = "(\0020b-spline coefficients \002)"; static char fmt_980[] = "(5x,8f9.4)"; static char fmt_985[] = "(\0020\002,\002spline values at selected grid points\002)"; /* System generated locals */ integer i__1, i__2, i__3; /* Builtin functions */ integer s_wsfe(cilist *), e_wsfe(void), do_fio(integer *, char *, ftnlen), s_rsfe(cilist *), e_rsfe(void); /* Subroutine */ int s_stop(char *, ftnlen); /* Local variables */ static integer idim, ipar[2], iopt, iwrk[80], kwrk, lwrk; static real c__[900], f[693]; static integer i__, j, l, m; static real s, u[21], v[11], z__[693]; static integer j0, j1, j2, j3, nuest, nvest; extern /* Subroutine */ int surev_(integer *, real *, integer *, real *, integer *, real *, real *, integer *, real *, integer *, real *, integer *, real *, integer *, integer *, integer *, integer *); static real ai; static integer nc; static real fp; static integer is, iw[32]; static real wk[128]; static integer mu, mv, nu, nv; static real tu[27], tv[17]; extern /* Subroutine */ int parsur_(integer *, integer *, integer *, integer *, real *, integer *, real *, real *, real *, integer *, integer *, integer *, real *, integer *, real *, real *, real *, real *, integer *, integer *, integer *, integer *); static integer ier; static real wrk[2000]; /* Fortran I/O blocks */ static cilist io___7 = { 0, 6, 0, fmt_900, 0 }; static cilist io___8 = { 0, 6, 0, fmt_905, 0 }; static cilist io___9 = { 0, 6, 0, fmt_910, 0 }; static cilist io___12 = { 0, 6, 0, fmt_915, 0 }; static cilist io___17 = { 0, 5, 0, fmt_920, 0 }; static cilist io___20 = { 0, 6, 0, fmt_925, 0 }; static cilist io___39 = { 0, 6, 0, fmt_935, 0 }; static cilist io___40 = { 0, 6, 0, fmt_940, 0 }; static cilist io___41 = { 0, 6, 0, fmt_945, 0 }; static cilist io___42 = { 0, 6, 0, fmt_950, 0 }; static cilist io___43 = { 0, 6, 0, fmt_955, 0 }; static cilist io___44 = { 0, 6, 0, fmt_960, 0 }; static cilist io___45 = { 0, 6, 0, fmt_965, 0 }; static cilist io___46 = { 0, 6, 0, fmt_970, 0 }; static cilist io___47 = { 0, 6, 0, fmt_960, 0 }; static cilist io___48 = { 0, 6, 0, fmt_965, 0 }; static cilist io___50 = { 0, 6, 0, fmt_975, 0 }; static cilist io___51 = { 0, 6, 0, fmt_980, 0 }; static cilist io___55 = { 0, 6, 0, fmt_985, 0 }; static cilist io___56 = { 0, 6, 0, fmt_905, 0 }; static cilist io___57 = { 0, 6, 0, fmt_910, 0 }; static cilist io___58 = { 0, 6, 0, fmt_915, 0 }; static cilist io___59 = { 0, 6, 0, fmt_925, 0 }; /* we generate the u-coordinates of the grid. */ mu = 21; i__1 = mu; for (i__ = 1; i__ <= i__1; ++i__) { u[i__ - 1] = (real) (i__ - 1); /* L10: */ } /* we generate the v-coordinates of the grid. */ mv = 11; i__1 = mv; for (i__ = 1; i__ <= i__1; ++i__) { v[i__ - 1] = u[(i__ << 1) - 2]; /* L20: */ } /* the dimension of the surface */ idim = 3; /* we fetch and print the surface co-ordinates at the grid points */ s_wsfe(&io___7); e_wsfe(); s_wsfe(&io___8); i__1 = mv; for (i__ = 1; i__ <= i__1; ++i__) { do_fio(&c__1, (char *)&v[i__ - 1], (ftnlen)sizeof(real)); } e_wsfe(); s_wsfe(&io___9); e_wsfe(); m = mu * mv; j0 = 0; i__1 = mu; for (i__ = 1; i__ <= i__1; ++i__) { s_wsfe(&io___12); do_fio(&c__1, (char *)&u[i__ - 1], (ftnlen)sizeof(real)); e_wsfe(); j1 = j0; i__2 = idim; for (l = 1; l <= i__2; ++l) { j2 = j1 + 1; j3 = j1 + mv; s_rsfe(&io___17); i__3 = j3; for (j = j2; j <= i__3; ++j) { do_fio(&c__1, (char *)&f[j - 1], (ftnlen)sizeof(real)); } e_rsfe(); s_wsfe(&io___20); i__3 = j3; for (j = j2; j <= i__3; ++j) { do_fio(&c__1, (char *)&f[j - 1], (ftnlen)sizeof(real)); } e_wsfe(); j1 += m; /* L30: */ } j0 += mv; /* L40: */ } /* we set up the dimension information */ nuest = 27; nvest = 17; lwrk = 2000; kwrk = 80; /* main loop for the different spline approximations */ for (is = 1; is <= 4; ++is) { switch (is) { case 1: goto L110; case 2: goto L120; case 3: goto L130; case 4: goto L140; } /* a smoothing surface with no periodicity conditions */ L110: iopt = 0; s = .07f; ipar[0] = 0; ipar[1] = 0; goto L200; /* a smoothing surface periodic in the v-variable */ L120: ipar[1] = 1; goto L200; /* a smoothing surface periodic in both variables */ L130: ipar[0] = 1; goto L200; /* finally we also calculate a least-squares spline surface */ /* with specified knots. */ L140: iopt = -1; nu = 11; nv = 11; j = 5; for (i__ = 1; i__ <= 3; ++i__) { ai = (real) (i__ * 5); tu[j - 1] = ai; tv[j - 1] = tu[j - 1]; ++j; /* L150: */ } /* determination of the spline surface. */ L200: parsur_(&iopt, ipar, &idim, &mu, u, &mv, v, f, &s, &nuest, &nvest, &nu, tu, &nv, tv, c__, &fp, wrk, &lwrk, iwrk, &kwrk, &ier); /* printing of the fitting results. */ if (iopt >= 0) { goto L210; } s_wsfe(&io___39); do_fio(&c__1, (char *)&ipar[0], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&ipar[1], (ftnlen)sizeof(integer)); e_wsfe(); goto L220; L210: s_wsfe(&io___40); do_fio(&c__1, (char *)&ipar[0], (ftnlen)sizeof(integer)); do_fio(&c__1, (char *)&ipar[1], (ftnlen)sizeof(integer)); e_wsfe(); s_wsfe(&io___41); do_fio(&c__1, (char *)&s, (ftnlen)sizeof(real)); e_wsfe(); L220: s_wsfe(&io___42); do_fio(&c__1, (char *)&fp, (ftnlen)sizeof(real)); do_fio(&c__1, (char *)&ier, (ftnlen)sizeof(integer)); e_wsfe(); s_wsfe(&io___43); do_fio(&c__1, (char *)&nu, (ftnlen)sizeof(integer)); e_wsfe(); s_wsfe(&io___44); e_wsfe(); s_wsfe(&io___45); i__1 = nu; for (i__ = 1; i__ <= i__1; ++i__) { do_fio(&c__1, (char *)&tu[i__ - 1], (ftnlen)sizeof(real)); } e_wsfe(); s_wsfe(&io___46); do_fio(&c__1, (char *)&nv, (ftnlen)sizeof(integer)); e_wsfe(); s_wsfe(&io___47); e_wsfe(); s_wsfe(&io___48); i__1 = nv; for (i__ = 1; i__ <= i__1; ++i__) { do_fio(&c__1, (char *)&tv[i__ - 1], (ftnlen)sizeof(real)); } e_wsfe(); nc = (nu - 4) * (nv - 4); s_wsfe(&io___50); e_wsfe(); j1 = 0; i__1 = idim; for (l = 1; l <= i__1; ++l) { j0 = j1 + 1; j1 += nc; s_wsfe(&io___51); i__2 = j1; for (j = j0; j <= i__2; ++j) { do_fio(&c__1, (char *)&c__[j - 1], (ftnlen)sizeof(real)); } e_wsfe(); /* L230: */ } /* evaluation of the spline surface. */ surev_(&idim, tu, &nu, tv, &nv, c__, u, &mu, v, &mv, z__, &c__693, wk, &c__128, iw, &c__32, &ier); s_wsfe(&io___55); e_wsfe(); s_wsfe(&io___56); i__1 = mv; for (i__ = 1; i__ <= i__1; i__ += 2) { do_fio(&c__1, (char *)&v[i__ - 1], (ftnlen)sizeof(real)); } e_wsfe(); s_wsfe(&io___57); e_wsfe(); j0 = 0; i__1 = mu; for (i__ = 1; i__ <= i__1; i__ += 4) { s_wsfe(&io___58); do_fio(&c__1, (char *)&u[i__ - 1], (ftnlen)sizeof(real)); e_wsfe(); j1 = j0; i__2 = idim; for (l = 1; l <= i__2; ++l) { j2 = j1 + 1; j3 = j1 + mv; s_wsfe(&io___59); i__3 = j3; for (j = j2; j <= i__3; j += 2) { do_fio(&c__1, (char *)&z__[j - 1], (ftnlen)sizeof(real)); } e_wsfe(); j1 += m; /* L240: */ } j0 += mv << 2; /* L250: */ } /* L300: */ } s_stop("", 0L); /* format statements. */ return 0; } /* MAIN__ */
30.672297
255
0.556008
[ "object" ]
a5604aadb46e524a3ebd34bfcc4e0eaf19285e03
943
h
C
clients/ios-osdk/PPCloak/GenericFrameworkProject/Views/UILocationListView/UILocationListViewCell/UILocationListViewCell.h
fdibernardo/PlusPrivacy
13086e7afd7340b8ccbab3f38e7511e55477279f
[ "MIT" ]
27
2017-07-25T15:03:02.000Z
2019-07-16T12:55:20.000Z
clients/ios-osdk/PPCloak/GenericFrameworkProject/Views/UILocationListView/UILocationListViewCell/UILocationListViewCell.h
fdibernardo/PlusPrivacy
13086e7afd7340b8ccbab3f38e7511e55477279f
[ "MIT" ]
11
2017-08-16T08:41:16.000Z
2019-10-27T13:39:29.000Z
clients/ios-osdk/PPCloak/GenericFrameworkProject/Views/UILocationListView/UILocationListViewCell/UILocationListViewCell.h
fdibernardo/PlusPrivacy
13086e7afd7340b8ccbab3f38e7511e55477279f
[ "MIT" ]
6
2017-06-16T08:14:40.000Z
2021-09-10T13:32:59.000Z
// // UILocationListViewCell.h // PPCloak // // Created by Costin Andronache on 3/31/17. // Copyright © 2017 RomSoft. All rights reserved. // #import <UIKit/UIKit.h> #import "MGSwipeTableCell.h" typedef void(^UILocationListCellUpdateCallback)(double latitude, double longitude); @interface UILocationListViewCellCallbacks : NSObject @property (strong, nonatomic) void(^onCoordinatesUpdate)(double latitude, double longitude); @property (strong, nonatomic) void(^onDelete)(); @end @interface UILocationListViewCellModel: NSObject @property (assign, nonatomic) double latitude; @property (assign, nonatomic) double longitude; @property (assign, nonatomic) NSInteger locationIndex; @property (assign, nonatomic) BOOL editable; @end @interface UILocationListViewCell: MGSwipeTableCell +(NSString*)identifierNibName; -(void)setupWithModel:(UILocationListViewCellModel*)model callbacks:(UILocationListViewCellCallbacks*)callbacks; @end
27.735294
112
0.793213
[ "model" ]
a567d2178c61d149dfefbc067bbe8cfdfc9161d7
829
h
C
Samples/XamlTreeView/cpp/Control/IntegerToIndentationConverter.h
lythix/Windows-universal-samples
773db9338b5de0b1058097f77ad3ac68dbc0a73d
[ "MIT" ]
29
2017-02-19T10:22:24.000Z
2021-06-29T19:10:29.000Z
Samples/XamlTreeView/cpp/Control/IntegerToIndentationConverter.h
asydhom/Windows-universal-samples
f6ad9bc1b5d85660b4544adebbc9a6d9db9a2246
[ "MIT" ]
1
2018-01-18T17:04:16.000Z
2018-01-18T17:04:16.000Z
Samples/XamlTreeView/cpp/Control/IntegerToIndentationConverter.h
asydhom/Windows-universal-samples
f6ad9bc1b5d85660b4544adebbc9a6d9db9a2246
[ "MIT" ]
9
2017-02-19T19:25:18.000Z
2020-01-14T16:39:11.000Z
#pragma once namespace TreeViewControl { [Windows::Foundation::Metadata::WebHostHidden] public ref class IntegerToIndentationConverter sealed : Windows::UI::Xaml::Data::IValueConverter { public: property int IndentMultiplier { int get() { return indentMultiplier; }; void set(int i) { indentMultiplier = i; }; } IntegerToIndentationConverter(); virtual Platform::Object^ Convert(Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language); virtual Platform::Object^ ConvertBack(Object^ value, Windows::UI::Xaml::Interop::TypeName targetType, Platform::Object^ parameter, Platform::String^ language); private: int indentMultiplier; }; }
34.541667
168
0.657419
[ "object" ]
a568183c2cc26f884615b93bc4bb9b9e26a7274f
976
h
C
algorithm/graph/floyd-warshall.h
isac322/algorithm
2ad83f0ab9f547fd3ac957b1357d36d2da585e09
[ "MIT" ]
null
null
null
algorithm/graph/floyd-warshall.h
isac322/algorithm
2ad83f0ab9f547fd3ac957b1357d36d2da585e09
[ "MIT" ]
null
null
null
algorithm/graph/floyd-warshall.h
isac322/algorithm
2ad83f0ab9f547fd3ac957b1357d36d2da585e09
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <limits> #include <cstddef> #include <algorithm> namespace FloydWarshall { using namespace std; const int &INF = numeric_limits<int>::max(); /* Graph G[i][j] : (i)->(j) edge weight if not exist INF */ vector<vector<int>> G; /* shortest distance dist[i][j] : (i) node to (j) node */ vector<vector<int>> dist; void init(int n) { G.resize(n, vector<int>(n, INF)); for (size_t i = 0; i < n; i++) G[i][i] = 0; } vector<vector<int>> &floydWarshall() { const size_t &n = G.size(); dist = G; for (size_t k = 0; k < n; k++) { for (size_t i = 0; i < n; i++) { if (dist[i][k] != INF) { for (size_t j = 0; j < n; j++) { if (dist[k][j] != INF) { dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); } } } } } return dist; } } /* 6 19 0 1 3 1 0 3 0 2 5 2 0 5 1 2 -3 1 3 4 3 1 4 1 4 7 4 1 7 2 3 2 3 2 2 2 4 6 4 2 6 3 4 2 4 3 2 3 5 2 5 3 2 4 5 5 5 4 5 */
13.369863
61
0.512295
[ "vector" ]
a56ac7a64e53eabc7feb8c876cc3508e57b3cd64
14,166
h
C
common/ArgonEngine/RenderSystem.h
skylersaleh/ArgonEngine
7847269b720892f7e9a64907ec9ee13ab80037fd
[ "MIT" ]
null
null
null
common/ArgonEngine/RenderSystem.h
skylersaleh/ArgonEngine
7847269b720892f7e9a64907ec9ee13ab80037fd
[ "MIT" ]
null
null
null
common/ArgonEngine/RenderSystem.h
skylersaleh/ArgonEngine
7847269b720892f7e9a64907ec9ee13ab80037fd
[ "MIT" ]
null
null
null
//Generated by the Argon Build System /** * @brief This file declares all the classes used in the Render System. * @file RenderSystem.h * @author Skyler Saleh **/ #ifndef RenderSystem_h #define RenderSystem_h #include "BoundingCube.h" #include "Matrix.h" #include "TypeInfo.h" #include <map> #include <ArgonEngine/Utility.h> #include "RenderSystemConstants.h" #include "VirtualResource.h" #include "VertexIterator.h" #include <stddef.h> #include <memory> #include <array> #include "Node.h" namespace Argon { /** * @brief This class is used to implement a camera in a scene. * @details * Each active camera can have multiple render targets. * And each render target can only belong to one camera. * Every camera that has a render target that is accessed when rendering the main camera is rendered to. * * Regular Render to Texture functionality can be implemented by setting a cameras render * target to a Texture(.tex) * * While rendering with a specific renderer can be done by setting the target to framebuffer(.fbo) * * To render to the screen you use the Render Target "{Virtual}/main_render_target.tex" **/ struct Camera: public ReflectionBase{ //! The map used to map individual render targets to cameras. static std::map<VirtualResource, Camera*>& all_cameras(){ static std::map<VirtualResource,Camera*> c; return c; } //! The transformation matrix of the camera. Matrix4f matrix; Matrix4f projection_matrix; Vector4f background_color=Argon::kBlackColor; Camera(){} //! Makes this camera the main one, that renders to the screen. void become_main_camera(){ all_cameras()["virtual://main_render_target.tex"]=this; } //! Makes this camera the main one, that renders to the screen. void become_main_camera2D(){ all_cameras()["virtual://2d_camera.tex"]=this; } Matrix4f inverse(); //! Returns a pointer to the camera that is currently rendering to the screen. static Camera* get_main_camera(){return all_cameras()["virtual://main_render_target.tex"];} static Camera* get_main_camera2D(){return all_cameras()["virtual://2d_camera.tex"];} ~Camera(); MAKE_VISIT_HEAD(Camera); }; typedef StringIntern StringType; const static size_t kRenderTypeSize[] = {4,2,1,1}; //!@brief converts a regular type to its render type. //!@tparam T The render type to convert. template<typename T> struct ToRenderType; template<> struct ToRenderType<float>{enum {type= kRenderTypeFloat}; }; template<> struct ToRenderType<uint8_t>{enum {type= kRenderTypeUByte}; }; template<> struct ToRenderType<int16_t>{enum {type= kRenderTypeShort}; }; template<> struct ToRenderType<int8_t>{enum {type= kRenderTypeByte}; }; //! @brief This class is used to represent a renderable mesh in the RenderSystem. struct VertexArray : public ReflectionBase { //! A tag used for debug purposes. StringIntern tag; //! A hint to the RenderSystem to optimize for frequent updates. bool updates_frequently; //! The raw vertex data in the array. std::vector<uint8_t> data; //! @brief The index data in the array. //! @details This is used to map vertex data to vertices, so vertices can be shared. std::vector<uint16_t> index_data; //! A vector containing all the attribute information. std::vector<VertexAttribPair> attributes; //! @brief Identifies the current version of the data. //! @details Increment this when the data in the array has been changed. int update_id; //! The draw mode to use. int draw_type; //! The stride between two vertices. ptrdiff_t stride; //! Recalculates the stride based on the added attributes. void recalc_stride(); float prim_size=5; VertexArray(); //! Returns true if attribute 's' is present in the vertex array. bool has_attribute(const StringIntern& s); //! An iterator to the start of the data of attribute 's' VertexIterator begin(const StringIntern& s); //! An iterator to the end of the data of attribute 's' VertexIterator end(const StringIntern& s){return begin(s) + vertex_count();} //! Returns a bounding cube that holds the bound of all vertices' data for attribute 's'. BoundingCube get_attribute_bounds(const StringIntern & s); BoundingCube get_attribute_bounds(const StringIntern & s) const {return const_cast<VertexArray*>(this)->get_attribute_bounds(s);} //! Returns the total number of vertices in the array. int vertex_count() const {if(stride) return data.size() / stride; else return 0;} //! Adds an attribute to the array. The array must be resized after this operation. template<typename T> void add_attribute(int components, const StringIntern& attrib){ VertexAttribPair pair; pair.attribute =attrib; pair.components=components; pair.to_float=&VertexAttribPair::_to_float_<T>; pair.from_float=&VertexAttribPair::_from_float_<T>; pair.type=ToRenderType<T>::type; pair.offset=stride; attributes.push_back(pair); recalc_stride(); } //! Resize the vertex array to contain 'size' vertices. void set_size(size_t size){data.resize(size * stride);} //! Returns a pointer to the start of the vertices data. const uint8_t * data_start() const {return &data[0];} //! Returns a pointer to the start of the vertices data. uint8_t * data_start(){return &data[0];} //! Returns a pointer to the start of the data of vertex 'x'. const uint8_t * vertex(size_t x) const {return &data[x * stride];} struct Buffer{ const uint8_t *d; size_t size; bool operator< (const Buffer&b)const{ for(size_t i=0;i<size;++i)if(d[i]!=b.d[i])return d[i]<b.d[i]; return d[size-1]<b.d[size-1]; } }; void optimize_vertices(); //! Returns a pointer to the start of the data of vertex 'x'. uint8_t * data_start(size_t x){return &data[x * stride];} //! Auto-generates an index array by numbering the vertices sequentially. void generate_indices(); void generate_indices_quad(); //! Append the data 'd' of size 'bytes_size' to the end of the array. void append_data(const uint8_t* d, int bytes_size); //! Sets the vertex array data by resizing the data to 'bytes_size' bytes, and copying the data from 'd'. void set_data(const uint8_t* d, int bytes_size); //! Returns the attrib_pair for attribute 's'. VertexAttribPair get_attribute(const StringIntern&s); MAKE_VISIT_HEAD(VertexArray); }; //!@brief Represents a light in the render system. struct Light : public InstanceList<Light>,public Node{ //! The lights falloff distance in meters. Larger values make the lights bounds larger. float distance=10; //! The strength of specular lighting from the light. float specular_power=1; //! The strength of diffuse lighting from the light. float diffuse_power=1; MAKE_VISIT_HEAD(Light) }; struct Uniforms: ReflectionBase{ std::map<StringIntern,std::vector<VirtualResource>> textures; std::map<StringIntern, std::vector<Matrix4f> > mat4; std::map<StringIntern, std::vector<Matrix3f> > mat3; std::map<StringIntern, std::vector<Matrix2f> > mat2; std::map<StringIntern, std::vector<Vector4f> > f4; std::map<StringIntern, std::vector<Vector3f> > f3; std::map<StringIntern, std::vector<Vector2f> > f2; std::map<StringIntern, std::vector<float> > f; VirtualResource & get_texture(const StringIntern &s){ auto &it = textures[s]; if(it.empty())it.push_back(VirtualResource()); return it[0]; } float & get_scalar(const StringIntern &s){ auto &it = f[s]; if(it.empty())it.push_back(0); return it[0]; } Matrix4f & get_mat4(const StringIntern &s){ auto &it = mat4[s]; if(it.empty())it.push_back(Argon::Matrix4f()); return it[0]; } Matrix3f & get_mat3(const StringIntern &s){ auto &it = mat3[s]; if(it.empty())it.push_back(Matrix3f()); return it[0]; } Matrix2f & get_mat2(const StringIntern &s){ auto &it = mat2[s]; if(it.empty())it.push_back(Matrix2f()); return it[0]; } Vector4f & get_fvec4(const StringIntern &s){ auto &it = f4[s]; if(it.empty())it.push_back(Vector4f(0,0,0,0)); return it[0]; } Vector3f & get_fvec3(const StringIntern &s){ auto &it = f3[s]; if(it.empty())it.push_back(Vector3f(0,0,0)); return it[0]; } Vector2f & get_fvec2(const StringIntern &s){ auto &it = f2[s]; if(it.empty())it.push_back(Vector2f(0,0)); return it[0]; } MAKE_VISIT_HEAD(Uniforms) }; //! @brief This class represents the material information when rendering. struct Material:public ReflectionBase{ Uniforms uniform; //! @brief A map of the shaders used in for rendering. //! @details //! Different Renderers require different shaders to work. So check //! the documentation of your chosen renderer to determine what shaders //! you can provide. VirtualResource shader= "shader://fallback.shd"; //! @brief The blending style to use. This is a bitmask of Argon::BlendFactor unsigned int blend= kBlendReplace; //! @brief a map of the uniforms used in the material. //! @details //! This allows your application to provide information to your shaders as //! uniform variables. These are used to control the appearance of objects. //! Read the shaders source to see what values can be modified. Vector4f &color=uniform.get_fvec4("color"); //! A tag used for debugging StringIntern name="Unnamed Material"; //! @brief The render flags to use when rendering. This is a bitfield of Argon::RenderFlags. //! @details //! This is bitwise AND'd with the Renderables render_flags, and controls things like masks. int render_flags=kRenderDefault; Material()=default; Material(const Material& m):Material(){operator=(m);} Material& operator = (const Material &m); bool is_transparent() const {return blend!=kBlendReplace;} MAKE_VISIT_HEAD(Material) }; static std::shared_ptr<Material> DefaultMaterial(new Material); static std::shared_ptr<Material> DebugMaterial(){ static std::shared_ptr<Material> m(new Material); m->shader="resource://debug.shd"; return m; } struct Frustrum:public ReflectionBase{ Frustrum(){} void extract_from_matrix(const Matrix4f &m); Frustrum(const Matrix4f & m){extract_from_matrix(m);} std::array<Vector3f, 6> planes; std::array<float, 6> distances; enum plane_mapping{ kLeft, kRight, kTop, kBottom, kFar, kNear }; enum collision_mapping{ kInside, kCollides, kOutside }; bool should_cull(const BoundingCube &c)const{ return false;if(c.size[0]==-1.)return false; return test_cube(c)==kOutside;} collision_mapping test_cube(const BoundingCube &c)const; MAKE_VISIT_HEAD(Frustrum) }; /** * @brief This class is used to create an object that is to be rendered. * @details * The Renderable class is used to describe the rendering attributes of an object * in the ArgonEngine. * * Each Renderable serves a node to a Doubly Linked List, which is used to iterate through * all Renderables in a scene. This means that the act of having a Renderable present in memory * causes it render(as long as their is a renderer present). **/ struct Renderable : public InstanceList<Renderable>, public Node { Uniforms uniform; Matrix4f& last_world_matrix=uniform.get_mat4("matrix"); Matrix4f& last_normal_matrix=uniform.get_mat4("normal_matrix"); Vector4f& last_color = uniform.get_fvec4("color"); //! The vertex array(mesh) to use when rendering the object. std::shared_ptr<VertexArray> vertex_array=nullptr; //! @brief Flags that control the rendering of an object such as the associated masks. //! @details //! This is a bitmask of RenderFlags, and is bitwised AND'd with the materials //! variable of the same name to generate an objects render flags. int render_flags=kRenderDefault; StringIntern tag="Unnamed Renderable"; //! Set to the number of the last vertex to render from the vertex array, or -1 to render all vertices. int end_vertex=-1; //! What cull style to use when rendering the object. int cull_face=kCullBackFaceCounterClockWise; //! The Material to use when rendering. std::shared_ptr<Material> material=DefaultMaterial; //! Returns true if the Renderable needs alpha blending. bool is_transparent() const {return material->is_transparent();} void update_transform(); Renderable()=default; Renderable(const Renderable& r):Renderable(){operator =(r);} Renderable& operator = (const Renderable &r); MAKE_VISIT_HEAD(Renderable) }; }; #endif // ifndef NeonRush_ARRenderSystem_h
39.45961
137
0.63243
[ "mesh", "render", "object", "vector" ]
a56e466f329ad9cfc83c9b06762d0c47958fa596
670
h
C
NSudo/stdafx.h
fossabot/NSudo
d24e41ab4d597a9e41072e6bc61570feaa16b63a
[ "MIT" ]
2
2020-08-31T05:15:38.000Z
2021-10-05T11:12:17.000Z
NSudo/stdafx.h
azraelrabbit/NSudo-1
e8ac4088177a2109e124544c9c91618c9b798cb2
[ "MIT" ]
null
null
null
NSudo/stdafx.h
azraelrabbit/NSudo-1
e8ac4088177a2109e124544c9c91618c9b798cb2
[ "MIT" ]
null
null
null
/* * PROJECT: NSudo * FILE: stdafx.h * PURPOSE: Precompiled Header * * LICENSE: The MIT License * * DEVELOPER: Mouri_Naruto (Mouri_Naruto AT Outlook.com) */ #pragma once #define NOMINMAX #pragma region targetver #include <SDKDDKVer.h> #define _WIN32_WINNT_WIN10_TH2 _WIN32_WINNT_WIN10 #define _WIN32_WINNT_WIN10_RS1 _WIN32_WINNT_WIN10 #pragma endregion #include "M2WindowsHelpers.h" #include "M2Win32GUIHelpers.h" #include <stdio.h> #include <tchar.h> #include <fstream> #include <map> #include <string> #include <vector> #include "NSudoVersion.h" #include "Resources/resource.h" #include <commctrl.h> #pragma comment(lib, "comctl32.lib")
16.75
56
0.737313
[ "vector" ]
a56fc6262ed119ebb2ed145a1b1073275212f724
3,613
h
C
Mysql/storage/ndb/memcache/src/schedulers/Trondheim.h
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T16:44:50.000Z
2015-12-24T16:44:50.000Z
Mysql/storage/ndb/memcache/src/schedulers/Trondheim.h
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
1
2015-12-24T18:23:56.000Z
2015-12-24T18:24:26.000Z
Mysql/storage/ndb/memcache/src/schedulers/Trondheim.h
clockzhong/WrapLAMP
fa7ad07da3f1759e74966a554befa47bbbbb8dd5
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2015, Oracle and/or its affiliates. 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 as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef NDBMEMCACHE_TRONDHEIM_SCHEDULER_H #define NDBMEMCACHE_TRONDHEIM_SCHEDULER_H #ifndef __cplusplus #error "This file is for C++ only" #endif #include <memcached/types.h> #include "ndbmemcache_config.h" #include "workitem.h" #include "Scheduler.h" #include "KeyPrefix.h" #include "ConnQueryPlanSet.h" #include "GlobalConfigManager.h" #include "SchedulerConfigManager.h" /* * Trondheim Scheduler * * The Trondheim scheduler pairs one Ndb thread (per cluster) with each * libevent worker thread. * Each Ndb thread uses a single Ndb object, and runs this loop: * Fetch items from workqueue * Poll for results * Prepare operations * Notify completions */ extern "C" { void * run_ndb_thread(void *v); } class Trondheim { public: class Global; // global singleton class Worker; // one object per memcached worker thread class WorkerConnection; // one object per {worker,connection} pair }; class Trondheim::Global : public GlobalConfigManager { public: Global(const scheduler_options *); ~Global(); WorkerConnection ** getWorkerConnectionPtr(int thd, int cluster) const { return (WorkerConnection **) getSchedulerConfigManagerPtr(thd, cluster); } void shutdown(); }; /* For each libevent worker thread in memcached, there is a Worker */ class Trondheim::Worker : public Scheduler { public: Worker() {}; ~Worker(); void init(int threadnum, const scheduler_options *options); void attach_thread(thread_identifier *) {} ; ENGINE_ERROR_CODE schedule(workitem *); void prepare(NdbTransaction *, NdbTransaction::ExecType, NdbAsynchCallback, workitem *, prepare_flags); void close(NdbTransaction *, workitem *); void release(workitem *); void add_stats(const char *, ADD_STAT, const void *); void shutdown(); bool global_reconfigure(Configuration *); protected: WorkerConnection * getConnection(int cluster_id) const { return * (global->getWorkerConnectionPtr(id, cluster_id)); } private: int id; Trondheim::Global * global; }; /* For each {connection, worker} tuple there is a WorkerConnection */ class Trondheim::WorkerConnection : public SchedulerConfigManager { friend class Trondheim::Global; friend class Trondheim::Worker; friend void * run_ndb_thread(void *); public: WorkerConnection(int, int); ~WorkerConnection(); void close(NdbTransaction *, workitem *); void release(NdbInstance *); protected: void shutdown(); void start(); void * runNdbThread(); ENGINE_ERROR_CODE schedule(workitem *); private: int pending_ops; struct workqueue * queue; Ndb *ndb; pthread_t ndb_thread_id; bool running; }; inline void Trondheim::Worker::close(NdbTransaction *tx, workitem *item) { getConnection(item->prefix_info.cluster_id)->close(tx, item); } #endif
26.566176
80
0.71907
[ "object" ]
a571e7826c557d861a191a58fed81dfa2d6dfb0f
4,156
h
C
fake_fd/include/fake_fd.h
raytheonbbn/weldr
88b0ad7104a305745490c33eb67afd6ee5871feb
[ "BSD-2-Clause" ]
15
2020-04-15T21:19:02.000Z
2021-12-20T22:41:37.000Z
fake_fd/include/fake_fd.h
raytheonbbn/weldr
88b0ad7104a305745490c33eb67afd6ee5871feb
[ "BSD-2-Clause" ]
6
2020-06-23T19:56:03.000Z
2021-07-31T13:22:59.000Z
fake_fd/include/fake_fd.h
raytheonbbn/weldr
88b0ad7104a305745490c33eb67afd6ee5871feb
[ "BSD-2-Clause" ]
2
2021-03-14T04:44:40.000Z
2021-06-24T05:40:36.000Z
// Copyright (c) 2019, Raytheon BBN Technologies, Inc. All Rights Reserved. // // This document does not contain technology or Technical Data controlled under either // the U.S. International Traffic in Arms Regulations or the U.S. Export Administration // // Distribution A: Approved for Public Release, Distribution Unlimited #ifndef FAKE_FD_H #define FAKE_FD_H #include <pthread.h> #include <semaphore.h> #include <poll.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "model.h" #define MAX_FAKE_FDS 1024 typedef struct fake_fd fake_fd; // Function table for implementation-specific routines. // // fake_fd is a generic library, intended to support different // file-descriptor-based IPC mechanisms. // This table defines the mechanism-specific behaviors for one mechanism. struct fd_control { //Creation routine for dummy fd. int (*create_fd)(); //Creation routine for implementation-specific struct. void *(*create_impl_struct)(int fd, void* args[]); //Getter for buffer struct when reading from an FFD. struct fake_filebuf *(*get_read_filebuf)(fake_fd*); //Getter for buffer struct when writing to an FFD. struct fake_filebuf *(*get_write_filebuf)(fake_fd*); //Getter for poll status int (*get_poll_status)(fake_fd*); //Handler for fcntl int (*handle_fcntl)(fake_fd* ffd, int cmd, int *ret, va_list args); //Handler for ioctl int (*handle_ioctl)(fake_fd* ffd, unsigned long request, int *ret, va_list args); //Parent pointer, for inheritance. struct fd_control *parent; }; // Return values for handler functions. #define FAKE_HANDLER_SUCCESS 0 // Handled the command. Return value is in ret. #define FAKE_HANDLER_SKIP 1 // Didn't handle this command. Try the parent. #define FAKE_HANDLER_REAL 2 // Send this command to the real function. // Default output value for handler-backed functions. // Returned if nothing handled the command. #define FAKE_HANDLER_DEFAULT 0 // Timeout in ms for polling on real file handles in our poll wrapper. #define FAKE_POLL_TIMEOUT 100 #define FAKE_SELECT_TIMEOUT 100000 struct fake_fd { //FD that this has taken over. int fd; int closed; int flags; //Generic plugin for type-specific data. void* impl_struct; struct fd_control* ctl; }; #define FD_BUFFER_SIZE 1024 struct fake_filebuf { char buf[FD_BUFFER_SIZE]; ssize_t off; ssize_t len; pthread_mutex_t lock; pthread_cond_t read_cond; }; // Global manager struct for fake file descriptors and file buffers. // This contains static arrays for each struct; // ensures this library doesn't monkey with the heap. // TODO: Allow recovery of free'd structs. struct fd_mgr { pthread_rwlock_t fd_lock; // rwlock for access to the fake fd array. pthread_rwlock_t buf_lock; // rwlock for access to the fake filebuf array. unsigned int next_fd; // Next available fake_fd index. unsigned int next_buf; // Next available fake_filebuf index. fake_fd fds[MAX_FAKE_FDS]; // fake file descriptor struct pool. struct fake_filebuf bufs[MAX_FAKE_FDS]; // fake file buffer struct pool. }; //Manager management int init_fd_mgr(); //FD management int create_fake_fd(struct fd_control* ctl, void* impl_params[]); fake_fd* get_fd_by_fd(int fd); fake_fd* remove_fd_by_fd(int fd); //File Buf management. struct fake_filebuf* create_fake_filebuf(); ssize_t get_avail(struct fake_filebuf* fb); //Override functions. int fake_close(int fd); int fake_read(int fd, char* buf, ssize_t size); int fake_write(int fd, const char* buf, ssize_t size); int fake_flush(int fd); //Default handler functions. int create_basic_fd(); int basic_handle_fcntl(fake_fd* ffd, int cmd, int *ret, va_list args); //Root-level control structure; should only be inherited. static struct fd_control basic_fd_ctl = { .create_fd = &create_basic_fd, .create_impl_struct = NULL, .get_read_filebuf = NULL, .get_write_filebuf = NULL, .get_poll_status = NULL, .handle_fcntl = &basic_handle_fcntl, .handle_ioctl = NULL, .parent = NULL }; #endif
29.267606
87
0.729066
[ "model" ]
a57208e4daa3a2c063de12007e56930bd0956279
150
h
C
Include/KAI/Translator/Precompiled.h
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
1
2018-06-16T17:53:43.000Z
2018-06-16T17:53:43.000Z
Include/KAI/Translator/Precompiled.h
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
null
null
null
Include/KAI/Translator/Precompiled.h
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
null
null
null
#include <algorithm> #include <string> #include <map> #include <vector> #include "Base.h" #include "Process.h" #include "Token.h" #include "Slice.h"
15
20
0.7
[ "vector" ]
a572f7d6dab9ae1e1a11b10296f0eab588280d93
49,277
c
C
src/mame2003/core_options.c
libretro/mame2003-plus-libretro
1fd30e32ec948da4227b5eb7af327fddd6c7115b
[ "RSA-MD" ]
145
2018-04-10T17:24:39.000Z
2022-03-27T17:39:03.000Z
src/mame2003/core_options.c
libretro/mame2003-plus-libretro
1fd30e32ec948da4227b5eb7af327fddd6c7115b
[ "RSA-MD" ]
779
2018-04-09T21:30:15.000Z
2022-03-31T06:38:07.000Z
src/mame2003/core_options.c
libretro/mame2003-plus-libretro
1fd30e32ec948da4227b5eb7af327fddd6c7115b
[ "RSA-MD" ]
152
2018-04-10T10:52:18.000Z
2022-03-09T08:24:16.000Z
/********************************************************************* core_options.c core option configurations used by mame2003-plus *********************************************************************/ #include "mame.h" #include "driver.h" #include <libretro.h> #include <string/stdstring.h> static struct retro_core_option_v2_definition default_options[OPT_end + 1]; /* need the plus one for the NULL entries at the end */ static struct retro_core_option_v2_definition effective_defaults[OPT_end + 1]; /* prevent saving corrupt cfgs when the save type does not match the type initialized */ bool save_protection; /****************************************************************************** private function prototypes ******************************************************************************/ static void set_variables(void); static void determine_core_options_version(struct retro_core_options_v2 *core_options_us); /****************************************************************************** external function prototypes and variables ******************************************************************************/ /* found in mame2003.c */ extern void retro_set_audio_buff_status_cb(void); extern void retro_describe_controls(void); extern const struct GameDriver *game_driver; extern retro_set_led_state_t led_state_cb; /* * Note that core options are not presented in order they are defined here, * but rather by their order in the OPT_ enum found in mame2003.h */ static struct retro_core_option_v2_definition option_def_four_way_emulation = { APPNAME"_four_way_emulation", "4-Way Joystick Emulation on 8-Way Joysticks", NULL, "Improves issues with hitting diagonals when playing 4-way games.", NULL, "cat_key_input", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_xy_device = { APPNAME"_xy_device", "X-Y Device", NULL, "Selects a specific x-y coordinates input device to read.", NULL, "cat_key_input", { { "mouse", NULL }, { "pointer", NULL }, { "lightgun", NULL }, { "disabled", NULL }, { NULL, NULL }, }, #if defined(__IOS__) "pointer" #else "mouse" #endif }; static struct retro_core_option_v2_definition option_def_crosshair_enabled = { APPNAME"_crosshair_enabled", "Show Lightgun Crosshairs", NULL, "Displays a generic crosshair for each player.", NULL, "cat_key_input", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_skip_disclaimer = { APPNAME"_skip_disclaimer", "Skip Disclaimer", NULL, "Bypasses a copyright warning from being displayed when loading content.", NULL, "cat_key_system", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_skip_warnings = { APPNAME"_skip_warnings", "Skip Warnings", NULL, "Bypasses a warning message from being displayed when loading content containing known issues.", NULL, "cat_key_system", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_display_setup = { APPNAME"_display_setup", "Display MAME Menu", NULL, "Toggles the visibility of the internal MAME menu.", NULL, "cat_key_system", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_brightness = { APPNAME"_brightness", "Brightness", NULL, "Modifies the brightness level being used.", NULL, "cat_key_video", { { "0.2", NULL }, { "0.3", NULL }, { "0.4", NULL }, { "0.5", NULL }, { "0.6", NULL }, { "0.7", NULL }, { "0.8", NULL }, { "0.9", NULL }, { "1.0", NULL }, { "1.1", NULL }, { "1.2", NULL }, { "1.3", NULL }, { "1.4", NULL }, { "1.5", NULL }, { "1.6", NULL }, { "1.7", NULL }, { "1.8", NULL }, { "1.9", NULL }, { "2.0", NULL }, { NULL, NULL }, }, "1.0" }; static struct retro_core_option_v2_definition option_def_gamma = { APPNAME"_gamma", "Gamma Correction", NULL, "Modifies the gamma level being used.", NULL, "cat_key_video", { { "0.5", NULL }, { "0.6", NULL }, { "0.7", NULL }, { "0.8", NULL }, { "0.9", NULL }, { "1.0", NULL }, { "1.1", NULL }, { "1.2", NULL }, { "1.3", NULL }, { "1.4", NULL }, { "1.5", NULL }, { "1.6", NULL }, { "1.7", NULL }, { "1.8", NULL }, { "1.9", NULL }, { "2.0", NULL }, { NULL, NULL }, }, "1.0" }; static struct retro_core_option_v2_definition option_def_display_artwork = { APPNAME"_display_artwork", "Display Artwork", NULL, "Restart core required. Used to display custom artwork when available.", NULL, "cat_key_artwork", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_art_resolution = { APPNAME"_art_resolution", "Artwork Resolution Multiplier", "Resolution Multiplier", "Restart core required. Increases the artwork resolution by the selected multiplier value.", NULL, "cat_key_artwork", { { "1", NULL }, { "2", NULL }, { "3", NULL }, { "4", NULL }, { "5", NULL }, { "6", NULL }, { "7", NULL }, { "8", NULL }, { NULL, NULL }, }, "1" }; static struct retro_core_option_v2_definition option_def_art_overlay_opacity = { APPNAME"_art_overlay_opacity", "Artwork Hardcoded Overlay Opacity", "Hardcoded Overlay Opacity", "Restart core required.", NULL, "cat_key_artwork", { { "default", NULL }, { "0", NULL }, { "1", NULL }, { "2", NULL }, { "3", NULL }, { "4", NULL }, { "5", NULL }, { "6", NULL }, { "7", NULL }, { "8", NULL }, { "9", NULL }, { "10", NULL }, { "11", NULL }, { "12", NULL }, { "13", NULL }, { "14", NULL }, { "15", NULL }, { "16", NULL }, { "17", NULL }, { "18", NULL }, { "19", NULL }, { "20", NULL }, { "21", NULL }, { "22", NULL }, { "23", NULL }, { "24", NULL }, { "25", NULL }, { "50", NULL }, { "70", NULL }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_neogeo_bios = { APPNAME"_neogeo_bios", "Specify Neo Geo BIOS", NULL, "Restart core required. Select alternative bios files.", NULL, NULL, { { "default", NULL }, { "euro", NULL }, { "euro-s1", NULL }, { "us", NULL }, { "us-e", NULL }, { "asia", NULL }, { "japan", NULL }, { "japan-s2", NULL }, { "unibios40", NULL }, { "unibios33", NULL }, { "unibios20", NULL }, { "unibios13", NULL }, { "unibios11", NULL }, { "unibios10", NULL }, { "debug", NULL }, { "asia-aes", NULL }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_stv_bios = { APPNAME"_stv_bios", "Specify Sega ST-V BIOS", NULL, "Restart core required. Select alternative bios files.", NULL, NULL, { { "default", NULL }, { "japan", NULL }, { "japana", NULL }, { "us", NULL }, { "japan_b", NULL }, { "taiwan", NULL }, { "europe", NULL }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_use_alt_sound = { APPNAME"_use_alt_sound", "Use CD Soundtrack", NULL, "Restart core required. Replaces original hardware sounds with external audio files when available.", NULL, "cat_key_audio", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_dialsharexy = { APPNAME"_dialsharexy", "Share 2 Player Dial Controls Across One X/Y Device", NULL, NULL, NULL, "cat_key_input", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_deadzone = { APPNAME"_deadzone", "Analog Deadzone", NULL, "Modifies the deadzone travel distance by a set percentage.", NULL, "cat_key_input", { { "0", "0%" }, { "5", "5%" }, { "10", "10%" }, { "15", "15%" }, { "20", "20%" }, { "25", "25%" }, { "30", "30%" }, { "35", "35%" }, { "40", "40%" }, { "45", "45%" }, { "50", "50%" }, { "55", "55%" }, { "60", "60%" }, { "65", "65%" }, { "70", "70%" }, { "75", "75%" }, { "80", "80%" }, { "85", "85%" }, { "90", "90%" }, { "95", "95%" }, { NULL, NULL }, }, "20" }; static struct retro_core_option_v2_definition option_def_tate_mode = { APPNAME"_tate_mode", "TATE Mode", NULL, "When enabled, the display will be rotated to the orientation used by actual hardware.", NULL, "cat_key_video", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_vector_resolution = { APPNAME"_vector_resolution", "Vector Resolution", "Resolution", "Restart core required.", NULL, "cat_key_vector", { { "640x480", NULL }, { "1024x768", NULL }, { "1280x960", NULL }, { "1440x1080", NULL }, { "1600x1200", NULL }, { "1707x1280", NULL }, { "original", NULL }, { NULL, NULL }, }, "1024x768" }; static struct retro_core_option_v2_definition option_def_vector_antialias = { APPNAME"_vector_antialias", "Vector Antialiasing", "Antialiasing", NULL, NULL, "cat_key_vector", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_vector_beam_width = { APPNAME"_vector_beam_width", "Vector Beam Width", "Beam Width", "Only used with antialiasing.", NULL, "cat_key_vector", { { "1", NULL }, { "1.2", NULL }, { "1.4", NULL }, { "1.6", NULL }, { "1.8", NULL }, { "2", NULL }, { "2.5", NULL }, { "3", NULL }, { "4", NULL }, { "5", NULL }, { "6", NULL }, { "7", NULL }, { "8", NULL }, { "9", NULL }, { "10", NULL }, { "11", NULL }, { "12", NULL }, { NULL, NULL }, }, "2" }; static struct retro_core_option_v2_definition option_def_vector_translucency = { APPNAME"_vector_translucency", "Vector Translucency", "Translucency", NULL, NULL, "cat_key_vector", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_vector_flicker = { APPNAME"_vector_flicker", "Vector Flicker", "Flicker", NULL, NULL, "cat_key_vector", { { "0", NULL }, { "10", NULL }, { "20", NULL }, { "30", NULL }, { "40", NULL }, { "50", NULL }, { "60", NULL }, { "70", NULL }, { "80", NULL }, { "90", NULL }, { "100", NULL }, { NULL, NULL }, }, "20" }; static struct retro_core_option_v2_definition option_def_vector_intensity = { APPNAME"_vector_intensity", "Vector Intensity", "Intensity", NULL, NULL, "cat_key_vector", { { "0.5", NULL }, { "1", NULL }, { "1.5", NULL }, { "2", NULL }, { "2.5", NULL }, { "3", NULL }, { NULL, NULL }, }, "1.5" }; static struct retro_core_option_v2_definition option_def_nvram_bootstraps = { APPNAME"_nvram_bootstraps", "NVRAM Bootstraps", NULL, "Used to automatically initialize games that otherwise require special startup procedures or configurations.", NULL, "cat_key_system", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_sample_rate = { APPNAME"_sample_rate", "Sample Rate", NULL, "Number of samples taken per second. Higher rates provide better quality audio.", NULL, "cat_key_audio", { { "8000", "8000 KHz" }, { "11025", "11025 KHz" }, { "22050", "22050 KHz" }, { "30000", "30000 KHz" }, { "44100", "44100 KHz" }, { "48000", "48000 KHz" }, { NULL, NULL }, }, "48000" }; static struct retro_core_option_v2_definition option_def_input_interface = { APPNAME"_input_interface", "Input Interface", NULL, "Configures which input types are being read.", NULL, "cat_key_input", { { "simultaneous", NULL }, { "retropad", NULL }, { "keyboard", NULL }, { NULL, NULL }, }, "simultaneous" }; static struct retro_core_option_v2_definition option_def_mame_remapping = { APPNAME"_mame_remapping", "Legacy Remapping", NULL, "Restart core required. Enables MAME menu input remapping.", NULL, "cat_key_system", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_frameskip = { APPNAME"_frameskip", "Frameskip", NULL, "Skips a number of frames from being displayed. Can be used to squeeze performance out of lower spec platforms.", NULL, "cat_key_video", { { "disabled", NULL }, { "1", NULL }, { "2", NULL }, { "3", NULL }, { "4", NULL }, { "5", NULL }, { "6", NULL }, { "7", NULL }, { "9", NULL }, { "10", NULL }, { "11", NULL }, { "auto", NULL }, { "auto_aggressive", "auto aggressive" }, { "auto_max", "auto max" }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_core_sys_subfolder = { APPNAME"_core_sys_subfolder", "Locate System Files Within a Subfolder", NULL, NULL, NULL, "cat_key_system", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_core_save_subfolder = { APPNAME"_core_save_subfolder", "Locate Save Files Within a Subfolder", NULL, NULL, NULL, "cat_key_system", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_autosave_hiscore = { APPNAME"_autosave_hiscore", "Autosave Hiscore", NULL, "Recommended to use default which will save the hiscore when closing content. Recursively will save repeatedly the entire time during gameplay. Disabled will bypass the use of the hiscore.dat file entirely.", NULL, "cat_key_system", { { "default", NULL }, { "recursively", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_cheat_input_ports = { APPNAME"_cheat_input_ports", "Dip Switch/Cheat Input Ports", NULL, NULL, NULL, "cat_key_input", { { "disabled", NULL }, { "enabled", NULL }, { NULL, NULL }, }, "disabled" }; static struct retro_core_option_v2_definition option_def_machine_timing = { APPNAME"_machine_timing", "Bypass Audio Skew", NULL, "Restart core required.", NULL, "cat_key_audio", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_digital_joy_centering = { APPNAME"_digital_joy_centering", "Center Joystick Axis for Digital Controls", NULL, "Emulates the center position of an analog joystick when using digital controls. Automatically returns the center position when no direction is being applied.", NULL, "cat_key_input", { { "enabled", NULL }, { "disabled", NULL }, { NULL, NULL }, }, "enabled" }; static struct retro_core_option_v2_definition option_def_cpu_clock_scale = { APPNAME"_cpu_clock_scale", "CPU Clock Scale", NULL, "Used to under or over clock the emulated CPU by a specified percentage.", NULL, NULL, { { "default", NULL }, { "25", "25%" }, { "30", "30%" }, { "35", "35%" }, { "40", "40%" }, { "45", "45%" }, { "50", "50%" }, { "55", "55%" }, { "60", "60%" }, { "65", "65%" }, { "70", "70%" }, { "75", "75%" }, { "80", "80%" }, { "85", "85%" }, { "90", "90%" }, { "95", "95%" }, { "105", "105%" }, { "110", "110%" }, { "115", "115%" }, { "120", "120%" }, { "125", "125%" }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_cyclone_mode = { APPNAME"_cyclone_mode", "Cyclone Mode", NULL, "Restart core required. Forces the selected cyclone mode to be used.", NULL, NULL, { { "default", NULL }, { "disabled", NULL }, { "Cyclone", NULL }, { "DrZ80", NULL }, { "Cyclone+DrZ80", NULL }, { "DrZ80(snd)", NULL }, { "Cyclone+DrZ80(snd)", NULL }, { NULL, NULL }, }, "default" }; static struct retro_core_option_v2_definition option_def_null = { NULL, NULL, NULL, NULL, NULL, NULL, {{0}}, NULL }; struct retro_core_option_v2_category option_cats_us[] = { { "cat_key_system", "System", "Configure system options." }, { "cat_key_input", "Input", "Configure input options." }, { "cat_key_audio", "Audio", "Configure audio options." }, { "cat_key_video", "Video", "Configure video options." }, { "cat_key_artwork", "Artwork", "Configure artwork options." }, { "cat_key_vector", "Vector", "Configure vector options." }, { NULL, NULL, NULL }, }; struct retro_core_options_v2 options_us = { option_cats_us, effective_defaults }; void init_core_options(void) { default_options[OPT_4WAY] = option_def_four_way_emulation; default_options[OPT_XY_DEVICE] = option_def_xy_device; default_options[OPT_CROSSHAIR_ENABLED] = option_def_crosshair_enabled; default_options[OPT_SKIP_DISCLAIMER] = option_def_skip_disclaimer; default_options[OPT_SKIP_WARNINGS] = option_def_skip_warnings; default_options[OPT_DISPLAY_SETUP] = option_def_display_setup; default_options[OPT_BRIGHTNESS] = option_def_brightness; default_options[OPT_GAMMA] = option_def_gamma; default_options[OPT_ARTWORK] = option_def_display_artwork; default_options[OPT_ART_RESOLUTION] = option_def_art_resolution; default_options[OPT_ART_OVERLAY_OPACITY] = option_def_art_overlay_opacity; default_options[OPT_NEOGEO_BIOS] = option_def_neogeo_bios; default_options[OPT_STV_BIOS] = option_def_stv_bios; default_options[OPT_USE_ALT_SOUND] = option_def_use_alt_sound; default_options[OPT_SHARE_DIAL] = option_def_dialsharexy; default_options[OPT_DEADZONE] = option_def_deadzone; default_options[OPT_TATE_MODE] = option_def_tate_mode; default_options[OPT_VECTOR_RESOLUTION] = option_def_vector_resolution; default_options[OPT_VECTOR_ANTIALIAS] = option_def_vector_antialias; default_options[OPT_VECTOR_BEAM] = option_def_vector_beam_width; default_options[OPT_VECTOR_TRANSLUCENCY] = option_def_vector_translucency; default_options[OPT_VECTOR_FLICKER] = option_def_vector_flicker; default_options[OPT_VECTOR_INTENSITY] = option_def_vector_intensity; default_options[OPT_NVRAM_BOOTSTRAP] = option_def_nvram_bootstraps; default_options[OPT_SAMPLE_RATE] = option_def_sample_rate; default_options[OPT_INPUT_INTERFACE] = option_def_input_interface; default_options[OPT_MAME_REMAPPING] = option_def_mame_remapping; default_options[OPT_FRAMESKIP] = option_def_frameskip; default_options[OPT_CORE_SYS_SUBFOLDER] = option_def_core_sys_subfolder; default_options[OPT_CORE_SAVE_SUBFOLDER] = option_def_core_save_subfolder; default_options[OPT_AUTOSAVE_HISCORE] = option_def_autosave_hiscore; default_options[OPT_CHEAT_INPUT_PORTS] = option_def_cheat_input_ports; default_options[OPT_MACHINE_TIMING] = option_def_machine_timing; default_options[OPT_DIGITAL_JOY_CENTERING] = option_def_digital_joy_centering; default_options[OPT_CPU_CLOCK_SCALE] = option_def_cpu_clock_scale; #if (HAS_CYCLONE || HAS_DRZ80) default_options[OPT_CYCLONE_MODE] = option_def_cyclone_mode; #endif default_options[OPT_end] = option_def_null; set_variables(); } static void set_variables(void) { static unsigned effective_options_count; /* the number of core options in effect for the current content */ int option_index = 0; for(option_index = 0; option_index < (OPT_end + 1); option_index++) { switch(option_index) { case OPT_4WAY: if(options.content_flags[CONTENT_JOYSTICK_DIRECTIONS] != 4) continue; break; case OPT_CROSSHAIR_ENABLED: if(!options.content_flags[CONTENT_LIGHTGUN]) continue; break; case OPT_STV_BIOS: if(!options.content_flags[CONTENT_STV]) continue; /* only offer BIOS selection when it is relevant */ break; case OPT_NEOGEO_BIOS: if(!options.content_flags[CONTENT_NEOGEO]) continue; /* only offer BIOS selection when it is relevant */ break; case OPT_USE_ALT_SOUND: if(!options.content_flags[CONTENT_ALT_SOUND]) continue; break; case OPT_SHARE_DIAL: if(!options.content_flags[CONTENT_DIAL]) continue; break; case OPT_VECTOR_RESOLUTION: case OPT_VECTOR_ANTIALIAS: case OPT_VECTOR_TRANSLUCENCY: case OPT_VECTOR_BEAM: case OPT_VECTOR_FLICKER: case OPT_VECTOR_INTENSITY: if(!options.content_flags[CONTENT_VECTOR]) continue; break; case OPT_NVRAM_BOOTSTRAP: if(!options.content_flags[CONTENT_NVRAM_BOOTSTRAP]) continue; break; } effective_defaults[effective_options_count] = default_options[option_index]; effective_options_count++; } determine_core_options_version( &options_us ); } void update_variables(bool first_time) { struct retro_led_interface ledintf; struct retro_variable var; int index; bool reset_control_descriptions = false; for(index = 0; index < OPT_end; index++) { var.value = NULL; var.key = default_options[index].key; if (environ_cb(RETRO_ENVIRONMENT_GET_VARIABLE, &var) && !string_is_empty(var.value)) /* the frontend sends a value for this core option */ { switch(index) { case OPT_INPUT_INTERFACE: if(strcmp(var.value, "retropad") == 0) options.input_interface = RETRO_DEVICE_JOYPAD; else if(strcmp(var.value, "keyboard") == 0) options.input_interface = RETRO_DEVICE_KEYBOARD; else options.input_interface = RETRO_DEVICE_KEYBOARD + RETRO_DEVICE_JOYPAD; break; case OPT_4WAY: if( (strcmp(var.value, "enabled") == 0) && (options.content_flags[CONTENT_JOYSTICK_DIRECTIONS] == 4) ) { if(!options.restrict_4_way) /* the option has just been toggled to "enabled" */ { options.restrict_4_way = true; reset_control_descriptions = true; /* games with rotated joysticks send different control descriptions in 4-way restrictor mode */ } } else { if(options.restrict_4_way) /* the option has just been toggled to "disabled" */ { options.restrict_4_way = false; reset_control_descriptions = true; /* games with rotated joysticks send different control descriptions in 4-way restrictor mode */ } } break; case OPT_XY_DEVICE: if(strcmp(var.value, "pointer") == 0) options.xy_device = RETRO_DEVICE_POINTER; else if(strcmp(var.value, "mouse") == 0) options.xy_device = RETRO_DEVICE_MOUSE; else if(strcmp(var.value, "lightgun") == 0) options.xy_device = RETRO_DEVICE_LIGHTGUN; else options.xy_device = RETRO_DEVICE_NONE; break; case OPT_CROSSHAIR_ENABLED: if(strcmp(var.value, "enabled") == 0) options.crosshair_enable = 1; else options.crosshair_enable = 0; break; case OPT_SKIP_DISCLAIMER: if(strcmp(var.value, "enabled") == 0) options.skip_disclaimer = true; else options.skip_disclaimer = false; break; case OPT_SKIP_WARNINGS: if(strcmp(var.value, "enabled") == 0) options.skip_warnings = true; else options.skip_warnings = false; break; case OPT_DISPLAY_SETUP: if(strcmp(var.value, "enabled") == 0) options.display_setup = 1; else options.display_setup = 0; break; case OPT_BRIGHTNESS: options.brightness = atof(var.value); if(!first_time) palette_set_global_brightness(options.brightness); break; case OPT_GAMMA: options.gamma = atof(var.value); if(!first_time) palette_set_global_gamma(options.gamma); break; case OPT_ARTWORK: if(strcmp(var.value, "enabled") == 0) options.use_artwork = ARTWORK_USE_ALL; else options.use_artwork = ARTWORK_USE_NONE; break; case OPT_ART_RESOLUTION: options.artwork_res = atoi(var.value); break; case OPT_ART_OVERLAY_OPACITY: if(strcmp(var.value, "default") == 0) options.overlay_opacity = ARTWORK_OVERLAY_DEFAULT; else { options.overlay_opacity = atoi(var.value); if (options.overlay_opacity < 0 ) options.overlay_opacity = 0; else if (options.overlay_opacity > 255) options.overlay_opacity = 255; } break; case OPT_STV_BIOS: if(!options.content_flags[CONTENT_STV]) break; if(options.content_flags[CONTENT_DIEHARD]) /* catch required bios for this one game. */ options.bios = "us"; else options.bios = (strcmp(var.value, "default") == 0) ? NULL : var.value; break; case OPT_NEOGEO_BIOS: if(!options.content_flags[CONTENT_NEOGEO]) break; options.bios = (strcmp(var.value, "default") == 0) ? NULL : var.value; break; case OPT_USE_ALT_SOUND: if(strcmp(var.value, "enabled") == 0) options.use_samples = true; else options.use_samples = false; break; case OPT_SHARE_DIAL: if(options.content_flags[CONTENT_DIAL] && (strcmp(var.value, "enabled") == 0)) options.dial_share_xy = 1; else options.dial_share_xy = 0; break; case OPT_DEADZONE: options.deadzone = atoi(var.value); break; case OPT_TATE_MODE: if(strcmp(var.value, "enabled") == 0) options.tate_mode = 1; else options.tate_mode = 0; break; case OPT_DIGITAL_JOY_CENTERING: if(strcmp(var.value, "enabled") == 0) options.digital_joy_centering = 1; else options.digital_joy_centering = 0; break; case OPT_VECTOR_RESOLUTION: { int width = 0; int height = 0; sscanf(var.value, "%dx%d", &width, &height); // if they are still 0, mame will set from driver resolution set options.vector_width = width; options.vector_height = height; } break; case OPT_VECTOR_ANTIALIAS: if(strcmp(var.value, "enabled") == 0) options.antialias = 1; /* integer: 1 to enable antialiasing on vectors _ does not work as of 2018/04/17*/ else options.antialias = 0; break; case OPT_VECTOR_BEAM: options.beam = atof(var.value); /* float: vector beam width */ break; case OPT_VECTOR_TRANSLUCENCY: if(strcmp(var.value, "enabled") == 0) options.translucency = 1; /* integer: 1 to enable translucency on vectors */ else options.translucency = 0; break; case OPT_VECTOR_FLICKER: options.vector_flicker = atof(var.value); break; case OPT_VECTOR_INTENSITY: options.vector_intensity_correction = atof(var.value); /* float: vector beam intensity */ break; case OPT_NVRAM_BOOTSTRAP: if(strcmp(var.value, "enabled") == 0) options.nvram_bootstrap = true; else options.nvram_bootstrap = false; break; case OPT_SAMPLE_RATE: options.samplerate = atoi(var.value); break; case OPT_MAME_REMAPPING: if(strcmp(var.value, "enabled") == 0) options.mame_remapping = true; else options.mame_remapping = false; if(first_time) save_protection = options.mame_remapping; else setup_menu_init(); break; case OPT_FRAMESKIP: if (strcmp(var.value, "auto") == 0) options.frameskip = 12; else if (strcmp(var.value, "auto_aggressive") == 0) options.frameskip = 13; else if(strcmp(var.value, "auto_max") == 0) options.frameskip = 14; else options.frameskip = atoi(var.value); retro_set_audio_buff_status_cb(); break; case OPT_CPU_CLOCK_SCALE: if(strcmp(var.value, "default") == 0) options.cpu_clock_scale = 1; else options.cpu_clock_scale = (double) atoi(var.value) / 100; break; case OPT_CORE_SYS_SUBFOLDER: if(strcmp(var.value, "enabled") == 0) options.system_subfolder = true; else options.system_subfolder = false; break; case OPT_CORE_SAVE_SUBFOLDER: if(strcmp(var.value, "enabled") == 0) options.save_subfolder = true; else options.save_subfolder = false; break; case OPT_AUTOSAVE_HISCORE: if(strcmp(var.value, "default") == 0) options.autosave_hiscore = 1; else if(strcmp(var.value, "recursively") == 0) options.autosave_hiscore = 2; else options.autosave_hiscore = 0; break; case OPT_CHEAT_INPUT_PORTS: if(strcmp(var.value, "enabled") == 0) options.cheat_input_ports = true; else options.cheat_input_ports = false; break; case OPT_MACHINE_TIMING: if(strcmp(var.value, "enabled") == 0) options.machine_timing = true; else options.machine_timing = false; break; #if (HAS_CYCLONE || HAS_DRZ80) case OPT_CYCLONE_MODE: if(strcmp(var.value, "default") == 0) options.cyclone_mode = 1; else if(strcmp(var.value, "Cyclone") == 0) options.cyclone_mode = 2; else if(strcmp(var.value, "DrZ80") == 0) options.cyclone_mode = 3; else if(strcmp(var.value, "Cyclone+DrZ80") == 0) options.cyclone_mode = 4; else if(strcmp(var.value, "DrZ80(snd)") == 0) options.cyclone_mode = 5; else if(strcmp(var.value, "Cyclone+DrZ80(snd)") == 0) options.cyclone_mode = 6; else /* disabled */ options.cyclone_mode = 0; break; #endif } } } options.activate_dcs_speedhack = true; /* formerly a core option, now always on. */ ledintf.set_led_state = NULL; environ_cb(RETRO_ENVIRONMENT_GET_LED_INTERFACE, &ledintf); led_state_cb = ledintf.set_led_state; if(reset_control_descriptions) /* one of the option changes has flagged a need to re-describe the controls */ { retro_describe_controls(); reset_control_descriptions = false; } } void set_content_flags(void) { int i = 0; extern struct GameDriver driver_neogeo; extern struct GameDriver driver_stvbios; const struct InputPortTiny *input = game_driver->input_ports; /************ DRIVERS WITH ALTERNATE SOUNDTRACKS ************/ for( i = 0; Machine->drv->sound[i].sound_type && i < MAX_SOUND; i++ ) { if (Machine->drv->sound[i].tag) if (strcmp("OST Samples", Machine->drv->sound[i].tag) == 0) { options.content_flags[CONTENT_ALT_SOUND] = true; } } /************ DRIVERS WITH MULTIPLE BIOS OPTIONS ************/ if (game_driver->clone_of == &driver_neogeo ||(game_driver->clone_of && game_driver->clone_of->clone_of == &driver_neogeo)) { options.content_flags[CONTENT_NEOGEO] = true; } else if (game_driver->clone_of == &driver_stvbios ||(game_driver->clone_of && game_driver->clone_of->clone_of == &driver_stvbios)) { options.content_flags[CONTENT_STV] = true; } /************ DIE HARD: ARCADE ************/ if(strcasecmp(game_driver->name, "diehard") == 0) options.content_flags[CONTENT_DIEHARD] = true; /************ DRIVERS WITH VECTOR VIDEO DISPLAYS ************/ if(Machine->drv->video_attributes & VIDEO_TYPE_VECTOR) options.content_flags[CONTENT_VECTOR] = true; /************ INPUT-BASED CONTENT FLAGS ************/ options.content_flags[CONTENT_JOYSTICK_DIRECTIONS] = 8; /* default behavior is 8-way joystick, even for 2-way games */ while ((input->type & ~IPF_MASK) != IPT_END) { /* skip analog extension fields */ if ((input->type & ~IPF_MASK) != IPT_EXTENSION) { switch (input->type & IPF_PLAYERMASK) { case IPF_PLAYER1: if (options.content_flags[CONTENT_PLAYER_COUNT] < 1) options.content_flags[CONTENT_PLAYER_COUNT] = 1; break; case IPF_PLAYER2: if (options.content_flags[CONTENT_PLAYER_COUNT] < 2) options.content_flags[CONTENT_PLAYER_COUNT] = 2; break; case IPF_PLAYER3: if (options.content_flags[CONTENT_PLAYER_COUNT] < 3) options.content_flags[CONTENT_PLAYER_COUNT] = 3; break; case IPF_PLAYER4: if (options.content_flags[CONTENT_PLAYER_COUNT] < 4) options.content_flags[CONTENT_PLAYER_COUNT] = 4; break; case IPF_PLAYER5: if (options.content_flags[CONTENT_PLAYER_COUNT] < 5) options.content_flags[CONTENT_PLAYER_COUNT] = 5; break; case IPF_PLAYER6: if (options.content_flags[CONTENT_PLAYER_COUNT] < 6) options.content_flags[CONTENT_PLAYER_COUNT] = 6; break; case IPF_PLAYER7: if (options.content_flags[CONTENT_PLAYER_COUNT] < 7) options.content_flags[CONTENT_PLAYER_COUNT] = 7; break; case IPF_PLAYER8: if (options.content_flags[CONTENT_PLAYER_COUNT] < 8) options.content_flags[CONTENT_PLAYER_COUNT] = 8; break; } if (input->type & IPF_4WAY) /* the controls use a 4-way joystick */ options.content_flags[CONTENT_JOYSTICK_DIRECTIONS] = 4; switch (input->type & ~IPF_MASK) { case IPT_JOYSTICKRIGHT_UP: case IPT_JOYSTICKRIGHT_DOWN: case IPT_JOYSTICKRIGHT_LEFT: case IPT_JOYSTICKRIGHT_RIGHT: case IPT_JOYSTICKLEFT_UP: case IPT_JOYSTICKLEFT_DOWN: case IPT_JOYSTICKLEFT_LEFT: case IPT_JOYSTICKLEFT_RIGHT: options.content_flags[CONTENT_DUAL_JOYSTICK] = true; break; case IPT_BUTTON1: if (options.content_flags[CONTENT_BUTTON_COUNT] < 1) options.content_flags[CONTENT_BUTTON_COUNT] = 1; break; case IPT_BUTTON2: if (options.content_flags[CONTENT_BUTTON_COUNT] < 2) options.content_flags[CONTENT_BUTTON_COUNT] = 2; break; case IPT_BUTTON3: if (options.content_flags[CONTENT_BUTTON_COUNT] < 3) options.content_flags[CONTENT_BUTTON_COUNT] = 3; break; case IPT_BUTTON4: if (options.content_flags[CONTENT_BUTTON_COUNT] < 4) options.content_flags[CONTENT_BUTTON_COUNT] = 4; break; case IPT_BUTTON5: if (options.content_flags[CONTENT_BUTTON_COUNT] < 5) options.content_flags[CONTENT_BUTTON_COUNT] = 5; break; case IPT_BUTTON6: if (options.content_flags[CONTENT_BUTTON_COUNT] <6 ) options.content_flags[CONTENT_BUTTON_COUNT] = 6; break; case IPT_BUTTON7: if (options.content_flags[CONTENT_BUTTON_COUNT] < 7) options.content_flags[CONTENT_BUTTON_COUNT] = 7; break; case IPT_BUTTON8: if (options.content_flags[CONTENT_BUTTON_COUNT] < 8) options.content_flags[CONTENT_BUTTON_COUNT] = 8; break; case IPT_BUTTON9: if (options.content_flags[CONTENT_BUTTON_COUNT] < 9) options.content_flags[CONTENT_BUTTON_COUNT] = 9; break; case IPT_BUTTON10: if (options.content_flags[CONTENT_BUTTON_COUNT] < 10) options.content_flags[CONTENT_BUTTON_COUNT] = 10; break; case IPT_PADDLE: options.content_flags[CONTENT_PADDLE] = true; break; case IPT_DIAL: options.content_flags[CONTENT_DIAL] = true; break; case IPT_TRACKBALL_X: case IPT_TRACKBALL_Y: options.content_flags[CONTENT_TRACKBALL] = true; break; case IPT_AD_STICK_X: case IPT_AD_STICK_Y: options.content_flags[CONTENT_AD_STICK] = true; break; case IPT_LIGHTGUN_X: case IPT_LIGHTGUN_Y: options.content_flags[CONTENT_LIGHTGUN] = true; break; case IPT_SERVICE : options.content_flags[CONTENT_HAS_SERVICE] = true; break; case IPT_TILT : options.content_flags[CONTENT_HAS_TILT] = true; break; } } ++input; } /************ DRIVERS FLAGGED IN CONTROLS.C WITH ALTERNATING CONTROLS ************/ if(game_driver->ctrl_dat->alternating_controls) { options.content_flags[CONTENT_ALTERNATING_CTRLS] = true; } /************ NUMBER OF DISTINCT CONTROL LAYOUTS ************/ options.content_flags[CONTENT_CTRL_COUNT] = options.content_flags[CONTENT_PLAYER_COUNT]; /* There may be a future need to have a ctrl_count different than player_count, * perhaps because of some alternating controls layout. This is a place to check * some condition and make the two numbers different if that should ever prove useful. */ if(false/*options.content_flags[CONTENT_ALTERNATING_CTRLS]*/) { options.content_flags[CONTENT_CTRL_COUNT] = 1; } /************ DRIVERS FLAGGED IN CONTROLS.C WITH 45-DEGREE JOYSTICK ROTATION ************/ if(game_driver->ctrl_dat->rotate_joy_45) options.content_flags[CONTENT_ROTATE_JOY_45] = true; /************ DRIVERS FLAGGED IN CONTROLS.C WITH MIRRORED CONTROLS ************/ if(game_driver->ctrl_dat->mirrored_controls) options.content_flags[CONTENT_MIRRORED_CTRLS] = true; /************ DRIVERS WITH NVRAM BOOTSTRAP PATCHES ************/ if(game_driver->bootstrap != NULL) options.content_flags[CONTENT_NVRAM_BOOTSTRAP] = true; /************ LOG THE STATE OF THE CONTENT FLAGS ************/ log_cb(RETRO_LOG_INFO, LOGPRE "==== BEGIN DRIVER CONTENT ATTRIBUTES ====\n"); if(options.content_flags[CONTENT_NEOGEO]) log_cb(RETRO_LOG_INFO, LOGPRE "* Neo Geo BIOS required.\n"); if(options.content_flags[CONTENT_STV]) log_cb(RETRO_LOG_INFO, LOGPRE "* STV BIOS required.\n"); if(options.content_flags[CONTENT_DIEHARD]) log_cb(RETRO_LOG_INFO, LOGPRE "* Die Hard: Arcade BIOS required.\n"); if(options.content_flags[CONTENT_ALT_SOUND]) log_cb(RETRO_LOG_INFO, LOGPRE "* Alternative soundtrack available.\n"); if(options.content_flags[CONTENT_VECTOR]) log_cb(RETRO_LOG_INFO, LOGPRE "* Vector display.\n"); log_cb(RETRO_LOG_INFO, LOGPRE "* Supports %i players with %i distinct controls.\n", options.content_flags[CONTENT_PLAYER_COUNT], options.content_flags[CONTENT_CTRL_COUNT]); log_cb(RETRO_LOG_INFO, LOGPRE "* Supports %i distinct button controls.\n", options.content_flags[CONTENT_BUTTON_COUNT]); if(options.content_flags[CONTENT_DIAL]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses a dial.\n"); if(options.content_flags[CONTENT_TRACKBALL]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses a trackball.\n"); if(options.content_flags[CONTENT_LIGHTGUN]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses a lightgun.\n"); if(options.content_flags[CONTENT_PADDLE]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses an paddle.\n"); if(options.content_flags[CONTENT_AD_STICK]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses an analog joystick.\n"); if(options.content_flags[CONTENT_HAS_SERVICE]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses a service button.\n"); if(options.content_flags[CONTENT_HAS_TILT]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses a tilt function.\n"); if(options.content_flags[CONTENT_ALTERNATING_CTRLS]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses alternating controls.\n"); if(options.content_flags[CONTENT_MIRRORED_CTRLS]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses multiplayer control labels.\n"); if(options.content_flags[CONTENT_ROTATE_JOY_45]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses joysticks rotated 45-degrees with respect to the cabinet.\n"); if(options.content_flags[CONTENT_DUAL_JOYSTICK]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses dual joysticks.\n"); if(options.content_flags[CONTENT_JOYSTICK_DIRECTIONS] == 4) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses 4-way joystick controls.\n"); else log_cb(RETRO_LOG_INFO, LOGPRE "* Uses 8-way joystick controls.\n"); if(options.content_flags[CONTENT_NVRAM_BOOTSTRAP]) log_cb(RETRO_LOG_INFO, LOGPRE "* Uses an NVRAM bootstrap controlled via core option.\n"); log_cb(RETRO_LOG_INFO, LOGPRE "==== END DRIVER CONTENT ATTRIBUTES ====\n"); } static void determine_core_options_version(struct retro_core_options_v2 *core_options_us) { unsigned version = 0; if (!environ_cb) return; if (!environ_cb(RETRO_ENVIRONMENT_GET_CORE_OPTIONS_VERSION, &version)) version = 0; if (version >= 2) { environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS_V2, core_options_us); } else { size_t i, j; size_t option_index = 0; size_t num_options = 0; struct retro_core_option_v2_definition *option_defs_us = core_options_us->definitions; struct retro_core_option_definition *option_v1_defs_us = NULL; struct retro_variable *variables = NULL; char **values_buf = NULL; /* Determine total number of options */ while (true) { if (option_defs_us[num_options].key) num_options++; else break; } if (version >= 1) { /* Allocate US array */ option_v1_defs_us = (struct retro_core_option_definition *) calloc(num_options + 1, sizeof(struct retro_core_option_definition)); /* Copy parameters from option_defs_us array */ for (i = 0; i < num_options; i++) { struct retro_core_option_v2_definition *option_def_us = &option_defs_us[i]; struct retro_core_option_value *option_values = option_def_us->values; struct retro_core_option_definition *option_v1_def_us = &option_v1_defs_us[i]; struct retro_core_option_value *option_v1_values = option_v1_def_us->values; option_v1_def_us->key = option_def_us->key; option_v1_def_us->desc = option_def_us->desc; option_v1_def_us->info = option_def_us->info; option_v1_def_us->default_value = option_def_us->default_value; /* Values must be copied individually... */ while (option_values->value) { option_v1_values->value = option_values->value; option_v1_values->label = option_values->label; option_values++; option_v1_values++; } } environ_cb(RETRO_ENVIRONMENT_SET_CORE_OPTIONS, option_v1_defs_us); } else { /* Allocate arrays */ variables = (struct retro_variable *)calloc(num_options + 1, sizeof(struct retro_variable)); values_buf = (char **)calloc(num_options, sizeof(char *)); if (!variables || !values_buf) goto error; /* Copy parameters from option_defs_us array */ for (i = 0; i < num_options; i++) { const char *key = option_defs_us[i].key; const char *desc = option_defs_us[i].desc; const char *default_value = option_defs_us[i].default_value; struct retro_core_option_value *values = option_defs_us[i].values; size_t buf_len = 3; size_t default_index = 0; values_buf[i] = NULL; if (desc) { size_t num_values = 0; /* Determine number of values */ while (true) { if (values[num_values].value) { /* Check if this is the default value */ if (default_value) if (strcmp(values[num_values].value, default_value) == 0) default_index = num_values; buf_len += strlen(values[num_values].value); num_values++; } else break; } /* Build values string */ if (num_values > 0) { buf_len += num_values - 1; buf_len += strlen(desc); values_buf[i] = (char *)calloc(buf_len, sizeof(char)); if (!values_buf[i]) goto error; strcpy(values_buf[i], desc); strcat(values_buf[i], "; "); /* Default value goes first */ strcat(values_buf[i], values[default_index].value); /* Add remaining values */ for (j = 0; j < num_values; j++) { if (j != default_index) { strcat(values_buf[i], "|"); strcat(values_buf[i], values[j].value); } } } } variables[option_index].key = key; variables[option_index].value = values_buf[i]; option_index++; } /* Set variables */ environ_cb(RETRO_ENVIRONMENT_SET_VARIABLES, variables); } error: /* Clean up */ if (option_v1_defs_us) { free(option_v1_defs_us); option_v1_defs_us = NULL; } if (values_buf) { for (i = 0; i < num_options; i++) { if (values_buf[i]) { free(values_buf[i]); values_buf[i] = NULL; } } free(values_buf); values_buf = NULL; } if (variables) { free(variables); variables = NULL; } } }
30.19424
211
0.580514
[ "vector" ]
a57c7f5c9ecbb498d8b5febe58de02ccda970cbc
6,383
h
C
submodules/hal/api/hdf5_impl/hdf5ExternalArray.h
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/api/hdf5_impl/hdf5ExternalArray.h
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/api/hdf5_impl/hdf5ExternalArray.h
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
/* * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #ifndef _HDF5EXTERNALARRAY_H #define _HDF5EXTERNALARRAY_H #include <cassert> #include <H5Cpp.h> #include "halDefs.h" // Hack to compile with various versions of HDF5 that aren't themselves compatible namespace H5 { #if H5_VERSION_GE(1, 10, 1) // Latest version. H5Location class exists and contains createGroup() and CommonFG doesn't. We Just use it. typedef H5Location PortableH5Location; #else // Versions 1.8.12 - 1.10.0 inclusive: H5Location exists, but doesn't contain createGroup() // Versions 1.8.11 and earlier: H5Location doesn't exist // In both cases, we stick with CommonFG typedef CommonFG PortableH5Location; #endif } namespace hal { /** * Wrapper for a 1-dimensional HDF5 array of fixed length. Array objects * are defined (and typed) by the input datatype. The array is paged into * memory chunk-by-chunk as needed (using the HDF5 cache as a back-end). * We can't use compiler tpying of the input objects (and instead just * expose the raw void* data) because the elements' sizes are not known * at compile time, and we don't want to move it around once its read. */ class HDF5ExternalArray { public: /** Constructor */ HDF5ExternalArray(); /** Destructor */ virtual ~HDF5ExternalArray(); /** Create a new dataset in specifed location * @param file Pointer to the HDF5 parent in which to create array * @param path Path within the file for the new array * @param dataType HDF5 Datatype describing contents of array * @param numElements Fixed length of the new array * @param cparms HDF5 options (ie chunking and compression etc) * @param chunksInBuffer * 0: load entire array into buffer * 1: use default chunking (from dataset) * N: buffersize will be N chunks. */ void create(H5::PortableH5Location* file, const H5std_string& path, const H5::DataType& dataType, hsize_t numElements, const H5::DSetCreatPropList* inCparms = NULL, hsize_t chunksInBuffer = 1); /** Load an existing dataset into memory * @param file Pointer to the HDF5 file in which to create array * @param path Path within the file for the new array * @param chunksInBuffer * 0: load entire array into buffer * 1: use default chunking (from dataset) * N: buffersize will be N chunks. */ void load(H5::PortableH5Location* file, const H5std_string& path, hsize_t chunksInBuffer = 1); /** Write the memory buffer back to the file */ void write(); /** Access the raw data at given index * @param i index of element to retrieve for reading */ const char* get(hsize_t i); /** Write the raw data at given index * @param i index of element to retrieve for updating */ char* getUpdate(hsize_t i); /** Access typed value within element in a raw data array * @param index Index of element (struct) in the array * @param offset Offset of value within struct (number of bytes) */ template <typename T> T getValue(hsize_t index, hsize_t offset) const; /** Write typed value within element in raw data array * @param index Index of element (struct) in the array * @param offset Offset of value within struct (number of bytes) * @param value New value to set */ template <typename T> void setValue(hsize_t index, hsize_t offset, T value); /** Write typed element in the the raw data index * @param offset OFfset of element in struct (number of bytes) */ /** Number of elements in array */ hsize_t getSize() const; /** Get the HDF5 Datatype */ const H5::DataType& getDataType() const; protected: /** Read chunk from file */ void page(hsize_t i); /** Pointer to file that owns this dataset */ H5::PortableH5Location* _file; /** Path of dataset in file */ H5std_string _path; /** Datatype for array */ H5::DataType _dataType; /** Dataspace (dimension information) of array */ H5::DataSpace _dataSpace; /** The HDF5 array object */ H5::DataSet _dataSet; /** Number of elements in the array (fixed length)*/ hsize_t _size; /** Size of chunk in elements */ hsize_t _chunkSize; /** Size of datatype in bytes */ hsize_t _dataSize; /** Index of first element in memory buffer */ hsize_t _bufStart; /** Index of last element in memory buffer */ hsize_t _bufEnd; /** Number of elements in memory buffer */ hsize_t _bufSize; /** In-memory buffer */ char* _buf; /** Dimensional information for in-memory buffer */ H5::DataSpace _chunkSpace; /** Flag saying we should write to disk on write * or page-out calls (set by getUpdate()) */ bool _dirty; private: HDF5ExternalArray(const HDF5ExternalArray&); HDF5ExternalArray& operator=(const HDF5ExternalArray&); }; // INLINE MEMBERS inline const char* HDF5ExternalArray::get(hsize_t i) { assert(i < _size); if (i < _bufStart || i > _bufEnd) { page(i); } assert((i - _bufStart) < _bufSize); return _buf + (i - _bufStart) * _dataSize; } inline char* HDF5ExternalArray::getUpdate(hsize_t i) { if (i >= _size) { throw hal_exception("error: attempt to write hdf5 array out of bounds"); } if (i < _bufStart || i > _bufEnd) { page(i); } _dirty = true; assert((i - _bufStart) < _bufSize); return _buf + (i - _bufStart) * _dataSize; } inline hsize_t HDF5ExternalArray::getSize() const { return _size; } template<typename T> inline T HDF5ExternalArray::getValue(hsize_t index, hsize_t offset) const { assert (offset + sizeof(T) <= _dataSize); //even though paging causes the class to change state, we //still consider getValue a const function since the array's //contents don't change. HDF5ExternalArray* stripConstThis = const_cast<HDF5ExternalArray*>(this); return *reinterpret_cast<const T*>(stripConstThis->get(index) + offset); } template<typename T> inline void HDF5ExternalArray::setValue(hsize_t index, hsize_t offset, T val) { assert (offset + sizeof(T) <= _dataSize); T* entry = reinterpret_cast<T*>(getUpdate(index) + offset); *entry = val; } inline const H5::DataType& HDF5ExternalArray::getDataType() const { return _dataType; } } #endif
30.251185
109
0.681968
[ "object" ]
a585b63c9e73e7efbf4ce78930b00194392250c3
949
h
C
core/connections/wim/packets/stickers_migration.h
Qt-Widgets/im-desktop-imported
85fed419229597bc10de59de268f5d898f853405
[ "Apache-2.0" ]
524
2016-03-16T10:17:28.000Z
2019-12-29T02:58:56.000Z
core/connections/wim/packets/stickers_migration.h
Qt-Widgets/im-desktop-imported-widgets-collection
85fed419229597bc10de59de268f5d898f853405
[ "Apache-2.0" ]
68
2016-03-16T16:23:17.000Z
2019-09-20T22:37:28.000Z
core/connections/wim/packets/stickers_migration.h
Qt-Widgets/im-desktop-imported-widgets-collection
85fed419229597bc10de59de268f5d898f853405
[ "Apache-2.0" ]
142
2016-03-16T10:25:03.000Z
2019-12-26T14:08:47.000Z
#pragma once #pragma once #include "../wim_packet.h" namespace core { namespace tools { class http_request_simple; } } namespace core { namespace tools { class binary_stream; } namespace wim { class stickers_migration : public wim_packet { std::vector<std::pair<int32_t, int32_t>> ids_; std::shared_ptr<core::tools::binary_stream> response_; int32_t init_request(std::shared_ptr<core::http_request_simple> _request) override; int32_t parse_response(std::shared_ptr<core::tools::binary_stream> _response) override; public: bool support_async_execution() const override; stickers_migration(wim_packet_params _params, std::vector<std::pair<int, int>> _ids); virtual ~stickers_migration(); std::shared_ptr<core::tools::binary_stream> get_response() const; }; } }
22.069767
99
0.630137
[ "vector" ]
a58ff5ed6b8a52047784874c68e6d20e089ea90c
5,989
h
C
data.sqlite/zDBStatementMetaData.h
djp952/data-sqlite
2aa5e4381869cc27f2a9c138f473bf095f26bc8f
[ "MIT" ]
null
null
null
data.sqlite/zDBStatementMetaData.h
djp952/data-sqlite
2aa5e4381869cc27f2a9c138f473bf095f26bc8f
[ "MIT" ]
null
null
null
data.sqlite/zDBStatementMetaData.h
djp952/data-sqlite
2aa5e4381869cc27f2a9c138f473bf095f26bc8f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // Copyright (c) 2008-2021 Michael G. Brehm // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //--------------------------------------------------------------------------- #ifndef __ZDBSTATEMENTMETADATA_H_ #define __ZDBSTATEMENTMETADATA_H_ #pragma once #include "AutoAnsiString.h" // Include AutoAnsiString declarations #include "StatementHandle.h" // Include StatementHandle declarations #include "zDBSchemaInfo.h" // Include zDBSchemaInfo declarations #include "zDBType.h" // Include zDBType declarations #include "zDBUtil.h" // Include zDBUtil declarations #pragma warning(push, 4) // Enable maximum compiler warnings using namespace System; using namespace System::Collections::Generic; using namespace System::Data; using namespace System::Runtime::InteropServices; BEGIN_NAMESPACE(zuki) BEGIN_NAMESPACE(data) BEGIN_NAMESPACE(dbms) //--------------------------------------------------------------------------- // Class zDBStatementMetaData (internal) // // Creates and maintains metadata for a zDBStatement instance. Broken out // for clarity, since it's a lot of very dry ugly code //--------------------------------------------------------------------------- ref class zDBStatementMetaData sealed { public: // Constructor // // Accepts a pointer to a StatementHandle wrapper class zDBStatementMetaData(StatementHandle* pStatement); //----------------------------------------------------------------------- // Member Functions // BuildSchemaTable // // Generates a DataTable containing result set schema information DataTable^ BuildSchemaTable(void); // GetCatalog // // Gets the catalog name for a statement column, if available String^ GetCatalogName(int ordinal); // GetName // // Gets the name associated with a statement column String^ GetName(int ordinal); // GetDataTypeName // // Gets the declared type name of the statement column String^ GetDataTypeName(int ordinal); // GetFieldType // // Gets the standard .NET data type for the specified column Type^ GetFieldType(int ordinal); // GetProviderSpecificDbType // // Gets the provider specific DbType for the specified column zDBType GetProviderSpecificDbType(int ordinal); // GetProviderSpecificFieldType // // Gets the provider specific data type for the specified column Type^ GetProviderSpecificFieldType(int ordinal); // GetSchemaName // // Gets the base schema name for a statement column, if available String^ GetSchemaName(int ordinal); // GetTableName // // Gets the base table name for a statement column, if available String^ GetTableName(int ordinal); //----------------------------------------------------------------------- // Properties // FieldCount // // Retrieves the number of field defined by the statement property int FieldCount { int get(void); } private: // STATIC CONSTRUCTOR static zDBStatementMetaData() { StaticConstruct(); } // DESTRUCTOR / FINALIZER ~zDBStatementMetaData() { this->!zDBStatementMetaData(); m_disposed = true; } !zDBStatementMetaData(); //----------------------------------------------------------------------- // Private Data Types // FieldTypes // // Defines the standard .NET and provider-specific Type^ for a field value struct FieldTypes { FieldTypes(Type^ standardType, Type^ providerType) : StandardType(standardType), ProviderType(providerType) {} bool IsNull(void) { return ((StandardType == nullptr) || (ProviderType == nullptr)); } initonly Type^ StandardType; // Standard type object initonly Type^ ProviderType; // Provider type object }; //----------------------------------------------------------------------- // Private Member Functions // AddSchemaTableRow // // Generates a single DataRow for the schema DataTable void AddSchemaTableRow(DataTable^ schema, int ordinal); // CacheFieldTypes // // Caches the data types for a field via it's ordinal void CacheFieldTypes(int ordinal); // StaticConstruct // // Called by the static constructor to initialize the declaration mapper static void StaticConstruct(void); //----------------------------------------------------------------------- // Member Variables bool m_disposed; // Object disposal flag StatementHandle* m_pStatement; // SQLite statement handle int m_fields; // Number of statement fields array<FieldTypes>^ m_types; // Instance type information static Dictionary<String^, FieldTypes>^ s_declarationMapper; static DataTable^ s_template; }; //--------------------------------------------------------------------------- END_NAMESPACE(dbms) END_NAMESPACE(data) END_NAMESPACE(zuki) #pragma warning(pop) #endif // __ZDBSTATEMENTMETADATA_H_
33.088398
89
0.634831
[ "object" ]
a590ea4a04d10653d746c57f233fd91e0516e9a0
2,810
h
C
code/include/Content/AssetLoader.h
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
4
2019-03-21T16:02:03.000Z
2020-04-09T08:53:29.000Z
code/include/Content/AssetLoader.h
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
24
2018-04-06T08:25:17.000Z
2020-10-19T11:01:09.000Z
code/include/Content/AssetLoader.h
Arzana/Plutonium
5a17c93e5072ac291b96347a4df196e1609fabe2
[ "MIT" ]
null
null
null
#pragma once #include "AssetCache.h" #include "Graphics/Vulkan/Pipelines/GraphicsPipeline.h" #include "Graphics/Text/Font.h" #include "Graphics/Models/Model.h" #include "Graphics/Models/ShapeType.h" namespace Pu { class CommandPool; /* Defines an object that can be used to load various assets from file. */ class AssetLoader { public: /* Initializes a new instance of an asset loader. */ AssetLoader(_In_ LogicalDevice &device, _In_ AssetCache &cache); AssetLoader(_In_ const AssetLoader&) = delete; AssetLoader(_In_ AssetLoader&&) = delete; _Check_return_ AssetLoader& operator =(_In_ const AssetLoader&) = delete; _Check_return_ AssetLoader& operator =(_In_ AssetLoader&&) = delete; /* Gets the logical device associated with the loader. */ _Check_return_ inline LogicalDevice& GetDevice(void) { return device; } /* Loads the renderpass with the specified subpasses and finalizes the renderpass. */ void PopulateRenderpass(_In_ Renderpass &renderpass, _In_ const vector<vector<wstring>> &shaders); /* Loads the shader program with the specified compute shader. */ void PopulateComputepass(_In_ ShaderProgram &program, _In_ const wstring &shader); /* Loads and stages a texture from a specific path. */ void InitializeTexture(_In_ Texture &texture, _In_ const wstring &path, _In_ const ImageInformation &info); /* Loads and stages a texture from 6 individual cube map image paths. */ void InitializeTexture(_In_ Texture &texture, _In_ const vector<wstring> &paths, _In_ const ImageInformation &info, _In_ const wstring &name); /* Stages a texture from the specified source. */ void InitializeTexture(_In_ Texture &texture, _In_ const byte *data, _In_ size_t size, _In_ wstring &&id); /* Generates mipmaps for the texture and makes it shader read only. */ void FinalizeTexture(_In_ Texture &texture, _In_ wstring &&id); /* Loads and stages a font from a specific path. */ void InitializeFont(_In_ Font &font, _In_ const wstring &path, _In_ Task &continuation); /* Loads and stages the meshes and materials. */ void InitializeModel(_In_ Model &model, _In_ const wstring &path, _In_ const DeferredRenderer &deferred, _In_ const LightProbeRenderer *probes); /* Creates a model with one mesh of the specified shape. */ void CreateModel(_In_ Model &model, _In_ ShapeType shape, _In_ const DeferredRenderer &deferred, _In_opt_ const LightProbeRenderer *probes); /* Stages the contents of the source buffer into the destination buffer and deletes the source buffer once completed. */ void StageBuffer(_In_ StagingBuffer &source, _In_ Buffer &destination, _In_ PipelineStageFlags dstStage, _In_ AccessFlags access, _In_ const wstring &name); private: AssetCache &cache; LogicalDevice &device; Queue &transferQueue, &graphicsQueue; }; }
50.178571
158
0.76121
[ "mesh", "object", "shape", "vector", "model" ]
a5923e62045573e7c8310bd1ac8bcdf4f5108bae
7,757
h
C
runtime/realm/redop.h
dycz0fx/legion
0cf9ddd60c227c219c8973ed0580ddc5887c9fb2
[ "Apache-2.0" ]
null
null
null
runtime/realm/redop.h
dycz0fx/legion
0cf9ddd60c227c219c8973ed0580ddc5887c9fb2
[ "Apache-2.0" ]
null
null
null
runtime/realm/redop.h
dycz0fx/legion
0cf9ddd60c227c219c8973ed0580ddc5887c9fb2
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // reduction ops for Realm #ifndef REALM_REDOP_H #define REALM_REDOP_H #include "realm/realm_config.h" #ifdef REALM_USE_CUDA #include "realm/cuda/cuda_redop.h" #endif namespace Realm { // a reduction op needs to look like this #ifdef NOT_REALLY_CODE class MyReductionOp { public: typedef int LHS; typedef int RHS; void apply(LHS& lhs, RHS rhs) const; // both of these are optional static const RHS identity; void fold(RHS& rhs1, RHS rhs2) const; }; #endif template <typename REDOP> struct ReductionOp; struct ReductionOpUntyped { size_t sizeof_this; // includes any identity val or user data after struct size_t sizeof_lhs; size_t sizeof_rhs; size_t sizeof_userdata; // extra data supplied to apply/fold void *identity; // if non-null, points into same object void *userdata; // if non-null, points into same object // CPU apply/fold functions - tolerate strided src/dst void (*cpu_apply_excl_fn)(void *lhs_ptr, size_t lhs_stride, const void *rhs_ptr, size_t rhs_stride, size_t count, const void *userdata); void (*cpu_apply_nonexcl_fn)(void *lhs_ptr, size_t lhs_stride, const void *rhs_ptr, size_t rhs_stride, size_t count, const void *userdata); void (*cpu_fold_excl_fn)(void *rhs1_ptr, size_t rhs1_stride, const void *rhs2_ptr, size_t rhs2_stride, size_t count, const void *userdata); void (*cpu_fold_nonexcl_fn)(void *rhs1_ptr, size_t rhs1_stride, const void *rhs2_ptr, size_t rhs2_stride, size_t count, const void *userdata); #ifdef REALM_USE_CUDA // CUDA kernels for apply/fold - these are not actually the functions, // but just information (e.g. host wrapper fnptr) that can be used // to look up the actual kernels void *cuda_apply_excl_fn, *cuda_apply_nonexcl_fn; void *cuda_fold_excl_fn, *cuda_fold_nonexcl_fn; #endif ReductionOpUntyped() : sizeof_this(sizeof(ReductionOpUntyped)) , sizeof_lhs(0) , sizeof_rhs(0) , sizeof_userdata(0) , identity(0) , userdata(0) , cpu_apply_excl_fn(0) , cpu_apply_nonexcl_fn(0) , cpu_fold_excl_fn(0) , cpu_fold_nonexcl_fn(0) #ifdef REALM_USE_CUDA , cuda_apply_excl_fn(0) , cuda_apply_nonexcl_fn(0) , cuda_fold_excl_fn(0) , cuda_fold_nonexcl_fn(0) #endif {} template <class REDOP> static ReductionOpUntyped *create_reduction_op(void) { ReductionOpUntyped *redop = new ReductionOp<REDOP>; return redop; } static ReductionOpUntyped *clone_reduction_op(const ReductionOpUntyped *redop); }; namespace ReductionKernels { template <typename REDOP, bool EXCL> void cpu_apply_wrapper(void *lhs_ptr, size_t lhs_stride, const void *rhs_ptr, size_t rhs_stride, size_t count, const void *userdata) { const REDOP *redop = static_cast<const REDOP *>(userdata); for(size_t i = 0; i < count; i++) { redop->template apply<EXCL>(*static_cast<typename REDOP::LHS *>(lhs_ptr), *static_cast<const typename REDOP::RHS *>(rhs_ptr)); lhs_ptr = static_cast<char *>(lhs_ptr) + lhs_stride; rhs_ptr = static_cast<const char *>(rhs_ptr) + rhs_stride; } } template <typename REDOP, bool EXCL> void cpu_fold_wrapper(void *rhs1_ptr, size_t rhs1_stride, const void *rhs2_ptr, size_t rhs2_stride, size_t count, const void *userdata) { const REDOP *redop = static_cast<const REDOP *>(userdata); for(size_t i = 0; i < count; i++) { redop->template fold<EXCL>(*static_cast<typename REDOP::RHS *>(rhs1_ptr), *static_cast<const typename REDOP::RHS *>(rhs2_ptr)); rhs1_ptr = static_cast<char *>(rhs1_ptr) + rhs1_stride; rhs2_ptr = static_cast<const char *>(rhs2_ptr) + rhs2_stride; } } }; #if defined(REALM_USE_CUDA) && defined(__NVCC__) // with a cuda-capable compiler, we'll automatically add cuda reduction // kernels if the REDOP class defines has_cuda_reductions AND it's true // this requires a bunch of SFINAE template-fu template <typename T> struct HasHasCudaReductions { struct YES { char dummy[1]; }; struct NO { char dummy[2]; }; struct AltnerativeDefinition { static const bool has_cuda_reductions = false; }; template <typename T2> struct Combined : public T2, public AltnerativeDefinition {}; template <typename T2, T2> struct CheckAmbiguous {}; template <typename T2> static NO has_member(CheckAmbiguous<const bool *, &Combined<T2>::has_cuda_reductions> *); template <typename T2> static YES has_member(...); const static bool value = sizeof(has_member<T>(0)) == sizeof(YES); }; template <typename T, bool OK> struct MaybeAddCudaReductions; template <typename T> struct MaybeAddCudaReductions<T, false> { static void if_member_exists(ReductionOpUntyped *redop) {}; static void if_member_is_true(ReductionOpUntyped *redop) {}; }; template <typename T> struct MaybeAddCudaReductions<T, true> { static void if_member_exists(ReductionOpUntyped *redop) { MaybeAddCudaReductions<T, T::has_cuda_reductions>::if_member_is_true(redop); } static void if_member_is_true(ReductionOpUntyped *redop) { Cuda::add_cuda_redop_kernels<T>(redop); } }; #endif template <typename REDOP> struct ReductionOp : public ReductionOpUntyped { // tacked on to end of ReductionOpUntyped struct typename REDOP::RHS identity_val; REDOP userdata_val; ReductionOp() : identity_val(REDOP::identity) , userdata_val() { sizeof_this = sizeof(ReductionOp<REDOP>); sizeof_lhs = sizeof(typename REDOP::LHS); sizeof_rhs = sizeof(typename REDOP::RHS); sizeof_userdata = sizeof(REDOP); identity = &identity_val; userdata = &userdata_val; cpu_apply_excl_fn = &ReductionKernels::cpu_apply_wrapper<REDOP, true>; cpu_apply_nonexcl_fn = &ReductionKernels::cpu_apply_wrapper<REDOP, false>; cpu_fold_excl_fn = &ReductionKernels::cpu_fold_wrapper<REDOP, true>; cpu_fold_nonexcl_fn = &ReductionKernels::cpu_fold_wrapper<REDOP, false>; #if defined(REALM_USE_CUDA) && defined(__NVCC__) // if REDOP defines/sets 'has_cuda_reductions' to true, try to // automatically build wrappers for apply_cuda<> and fold_cuda<> MaybeAddCudaReductions<REDOP, HasHasCudaReductions<REDOP>::value>::if_member_exists(this); #endif } protected: }; }; // namespace Realm //include "redop.inl" #endif // ifndef REALM_REDOP_H
38.40099
142
0.648575
[ "object" ]
a59d69ede2ff8dbcb589d95a926c119a6383d013
1,020
h
C
sdktools/mtscript/inc/threadlock.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
sdktools/mtscript/inc/threadlock.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
sdktools/mtscript/inc/threadlock.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#ifndef THREADLOCK_H #define THREADLOCK_H class CThreadLock { public: CThreadLock() { InitializeCriticalSection(&_csAccess); } ~CThreadLock() { DeleteCriticalSection(&_csAccess); } void ThreadLock() { EnterCriticalSection(&_csAccess); } void ThreadUnLock() { LeaveCriticalSection(&_csAccess); } private: CRITICAL_SECTION _csAccess; // Used to control access to member data // Do not allow this object to be copied. CThreadLock(const CThreadLock &that); operator=(const CThreadLock &that); }; class CAutoLock { public: CAutoLock(CThreadLock *pThis) : _pThis(pThis) { _pThis->ThreadLock(); } ~CAutoLock() { _pThis->ThreadUnLock(); } private: CThreadLock *_pThis; }; // // // LOCK_LOCALS() should be used whenever access to thread-safe member data // is needed. // #define LOCK_LOCALS(pObj) CAutoLock local_lock(pObj); #endif
18.888889
75
0.610784
[ "object" ]
a5a1773118cd5d2470300cd423e8679004e3c87e
274
h
C
include/Pass/constant_propagation.h
luooofan/hblzbd_compiler
c3dac8bc4236dbca2b834aaad63ff27a7f136c8d
[ "MIT" ]
6
2021-09-27T06:55:05.000Z
2022-03-23T15:55:08.000Z
include/Pass/constant_propagation.h
luooofan/hblzbd_compiler
c3dac8bc4236dbca2b834aaad63ff27a7f136c8d
[ "MIT" ]
null
null
null
include/Pass/constant_propagation.h
luooofan/hblzbd_compiler
c3dac8bc4236dbca2b834aaad63ff27a7f136c8d
[ "MIT" ]
null
null
null
#ifndef __CONSTANT_PROPAGATION_H__ #define __CONSTANT_PROPAGATION_H__ #include "./pass_manager.h" #include "./reach_define.h" class ConstantPropagation : public Transform { public: ConstantPropagation(Module **m) : Transform(m) {} void Run(); }; #endif
19.571429
52
0.718978
[ "transform" ]
a5a4b4e6549b2f0ad951d4d2d5617e3cc2bb8ba8
2,677
h
C
src/image_wrap.h
brewster/magick
1dd829f463a72cf09da70b450edf8a55aad09039
[ "MIT" ]
null
null
null
src/image_wrap.h
brewster/magick
1dd829f463a72cf09da70b450edf8a55aad09039
[ "MIT" ]
1
2016-05-18T16:10:52.000Z
2017-06-06T14:13:17.000Z
src/image_wrap.h
brewster/magick
1dd829f463a72cf09da70b450edf8a55aad09039
[ "MIT" ]
null
null
null
#ifndef __IMAGE_H__ #define __IMAGE_H__ #include <stdio.h> #include <wand/MagickWand.h> class ImageWrap { public: // Initialize the necessary components needed by ImageWrap // Should be called before using any ImageWrap objects static void Init(); // Let go of any setup created by Init() // Should be called after use of ImageWrap objects is over static void Shutdown(); // Create a new ImageWrap from the given data & size ImageWrap(void *, size_t); // Destruct an ImageWrap ~ImageWrap(); // Get the blob of the image as a (char *) and (size_t) which // represents the length of the blob void GetBlob(char *&, size_t &); // Get the dimensions of the ImageWrap in a (char *) // of the format "#{w}x#{h}" set into the given reference void GetDimensionString(char *&); // Set the format of the ImageWrap ("jpg", "png", etc) void SetFormat(char *); // Perform a resize operation to the given width and height void Resize(int, int); // Perform a crop to the given width and height void Crop(int, int); // Perform a ResizeToFill operation to the given width and height. // This is a resize operation very similar to that employed on Flickr, // where the resize uses the largest portion of the image possible. // If we are resizing a image which is wider than it is tall down to // a square image, the result will use the entire vertical dimension, // and then center on the horizontal dimension. void ResizeToFill(int, int); // Set the opacity of the ImageWrap, as a float - where 0.0 represents // full transparency and 1.0 represents full opacity. void Opacity(float); // Perform a blur on the image using the passed sigma and optional radius void Blur(int, int); // Simulate a charcoal drawing. Accepts the sigma and optional radius void Charcoal(int, int); // Simulate an oil painting. Accepts optional radius void Paint(int); // Applies an effect similar to a sepia tone with threshold void Sepia(int); // Get the underlying MagickWand for the ImageWrap. This object // is not a copy, but rather a reference to the actual MagickWand. MagickWand* GetWand(void); private: // Release the base MagickWand (as part of destruction) void ReleaseBaseWand(); /* * Private variables */ // The MagickWand used for internal operations MagickWand *baseWand; /* * Inline methods */ // Get the current width of the ImageWrap size_t GetOriginalWidth() { return MagickGetImageWidth(this->baseWand); } // Get the current height of the ImageWrap size_t GetOriginalHeight() { return MagickGetImageHeight(this->baseWand); } }; #endif
27.040404
75
0.706014
[ "object" ]
a5a5e6eb5a4db1f88c69a263523a813e13c33100
2,110
h
C
include/camera.h
VIGameStudio/PhotonCaster
947e62e2d8f65bd3526f3672436812b22816caa8
[ "MIT" ]
null
null
null
include/camera.h
VIGameStudio/PhotonCaster
947e62e2d8f65bd3526f3672436812b22816caa8
[ "MIT" ]
null
null
null
include/camera.h
VIGameStudio/PhotonCaster
947e62e2d8f65bd3526f3672436812b22816caa8
[ "MIT" ]
null
null
null
#ifndef CAMERA_H #define CAMERA_H #include <iostream> #include <glm/glm.hpp> #include <glm/gtx/quaternion.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/string_cast.hpp> using namespace glm; using namespace std; namespace graphics { const static vec3 UP = vec3 (0,1,0); const static vec3 FORWARD = vec3 (0,0,-1); const static vec3 RIGHT = vec3 (1,0,0); struct Camera { Camera () : Camera (vec3 (), FORWARD, UP, 70.f) {} Camera (const vec3& pos, const vec3& target, const vec3& up, const float fov) : position (pos), m_fov (fov) { orientation = glm::conjugate (glm::toQuat (glm::lookAt (pos, target, up))); } vec3 position; quat orientation; inline void Perspective (const float& fov, const float& aspect, const float& znear, const float& zfar) { m_fov = fov; m_aspect = aspect; m_projection = glm::perspective (fov, aspect, znear, zfar); } inline void Update () { m_view = glm::lookAt (position, position+forward (), up ()); m_combined = m_projection * m_view; } inline float fov () const { return m_fov; } inline float aspect () const { return m_aspect; } inline vec3 up () const { return orientation * UP; } inline vec3 forward () const { return orientation * FORWARD; } inline vec3 right () const { return orientation * RIGHT; } inline mat4 projection () const { return m_projection; } inline mat4 view () const { return m_view; } inline mat4 combined () const { return m_combined; } inline void print () const { cout << "pos: "<<glm::to_string (position)<<"\n"; cout << "ori: fquat(" << orientation.w << ", " << orientation.x << ", " << orientation.y << ", " << orientation.z << ")\n"; } private: mat4 m_projection; mat4 m_view; mat4 m_combined; float m_fov; float m_aspect; }; } #endif // CAMERA_H
28.133333
110
0.562559
[ "transform" ]
a5a6acd7480581e8e4725b33e7969f87cd0f7745
39,101
c
C
third_party/chibicc/preprocess.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
third_party/chibicc/preprocess.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
third_party/chibicc/preprocess.c
appotry/cosmopolitan
af4687cc3f2331a23dc336183ab58fe001cda082
[ "ISC" ]
null
null
null
// This file implements the C preprocessor. // // The preprocessor takes a list of tokens as an input and returns a // new list of tokens as an output. // // The preprocessing language is designed in such a way that that's // guaranteed to stop even if there is a recursive macro. // Informally speaking, a macro is applied only once for each token. // That is, if a macro token T appears in a result of direct or // indirect macro expansion of T, T won't be expanded any further. // For example, if T is defined as U, and U is defined as T, then // token T is expanded to U and then to T and the macro expansion // stops at that point. // // To achieve the above behavior, we attach for each token a set of // macro names from which the token is expanded. The set is called // "hideset". Hideset is initially empty, and every time we expand a // macro, the macro name is added to the resulting tokens' hidesets. // // The above macro expansion algorithm is explained in this document // written by Dave Prossor, which is used as a basis for the // standard's wording: // https://github.com/rui314/chibicc/wiki/cpp.algo.pdf #include "libc/log/libfatal.internal.h" #include "libc/mem/arena.h" #include "libc/stdio/stdio.h" #include "third_party/chibicc/chibicc.h" #include "third_party/chibicc/kw.h" typedef struct CondIncl CondIncl; typedef struct Hideset Hideset; typedef struct MacroArg MacroArg; typedef enum { STR_NONE, STR_UTF8, STR_UTF16, STR_UTF32, STR_WIDE, } StringKind; struct MacroArg { MacroArg *next; char *name; bool is_va_args; Token *tok; }; // `#if` can be nested, so we use a stack to manage nested `#if`s. struct CondIncl { CondIncl *next; enum { IN_THEN, IN_ELIF, IN_ELSE } ctx; Token *tok; bool included; }; struct Hideset { Hideset *next; char *name; }; HashMap macros; static CondIncl *cond_incl; static HashMap pragma_once; static int include_next_idx; static Token *preprocess2(Token *); static Macro *find_macro(Token *); static inline bool is_hash(Token *tok) { return tok->at_bol && tok->len == 1 && tok->loc[0] == '#'; } // Some preprocessor directives such as #include allow extraneous // tokens before newline. This function skips such tokens. static Token *skip_line(Token *tok) { if (tok->at_bol) return tok; warn_tok(tok, "extra token"); while (tok->at_bol) tok = tok->next; return tok; } static Token *copy_token(Token *tok) { Token *t = alloc_token(); *t = *tok; t->next = NULL; return t; } static Token *new_eof(Token *tok) { Token *t = copy_token(tok); t->kind = TK_EOF; t->len = 0; return t; } static Hideset *new_hideset(char *name) { Hideset *hs = calloc(1, sizeof(Hideset)); hs->name = name; return hs; } static Hideset *hideset_union(Hideset *hs1, Hideset *hs2) { Hideset head = {}; Hideset *cur = &head; for (; hs1; hs1 = hs1->next) { cur = cur->next = new_hideset(hs1->name); } cur->next = hs2; return head.next; } static bool hideset_contains(Hideset *hs, char *s, int len) { for (; hs; hs = hs->next) { if (strlen(hs->name) == len && !strncmp(hs->name, s, len)) { return true; } } return false; } static Hideset *hideset_intersection(Hideset *hs1, Hideset *hs2) { Hideset head = {}; Hideset *cur = &head; for (; hs1; hs1 = hs1->next) { if (hideset_contains(hs2, hs1->name, strlen(hs1->name))) { cur = cur->next = new_hideset(hs1->name); } } return head.next; } static Token *add_hideset(Token *tok, Hideset *hs) { Token head = {}; Token *cur = &head; for (; tok; tok = tok->next) { Token *t = copy_token(tok); t->hideset = hideset_union(t->hideset, hs); cur = cur->next = t; } return head.next; } // Append tok2 to the end of tok1. static Token *append(Token *tok1, Token *tok2) { if (tok1->kind == TK_EOF) return tok2; Token head = {}; Token *cur = &head; for (; tok1->kind != TK_EOF; tok1 = tok1->next) cur = cur->next = copy_token(tok1); cur->next = tok2; return head.next; } static Token *skip_cond_incl2(Token *tok) { unsigned char kw; while (tok->kind != TK_EOF) { if (is_hash(tok) && (kw = GetKw(tok->next->loc, tok->next->len))) { if (kw == KW_IF || kw == KW_IFDEF || kw == KW_IFNDEF) { tok = skip_cond_incl2(tok->next->next); continue; } if (kw == KW_ENDIF) { return tok->next->next; } } tok = tok->next; } return tok; } // Skip until next `#else`, `#elif` or `#endif`. // Nested `#if` and `#endif` are skipped. static Token *skip_cond_incl(Token *tok) { unsigned char kw; while (tok->kind != TK_EOF) { if (is_hash(tok) && (kw = GetKw(tok->next->loc, tok->next->len))) { if (kw == KW_IF || kw == KW_IFDEF || kw == KW_IFNDEF) { tok = skip_cond_incl2(tok->next->next); continue; } if (kw == KW_ELIF || kw == KW_ELSE || kw == KW_ENDIF) { break; } } tok = tok->next; } return tok; } // Double-quote a given string and returns it. static char *quote_string(char *str) { int bufsize = 3; for (int i = 0; str[i]; i++) { if (str[i] == '\\' || str[i] == '"') bufsize++; bufsize++; } char *buf = calloc(1, bufsize); char *p = buf; *p++ = '"'; for (int i = 0; str[i]; i++) { if (str[i] == '\\' || str[i] == '"') *p++ = '\\'; *p++ = str[i]; } *p++ = '"'; *p++ = '\0'; return buf; } static Token *new_str_token(char *str, Token *tmpl) { char *buf = quote_string(str); return tokenize(new_file(tmpl->file->name, tmpl->file->file_no, buf)); } // Copy all tokens until the next newline, terminate them with // an EOF token and then returns them. This function is used to // create a new list of tokens for `#if` arguments. static Token *copy_line(Token **rest, Token *tok) { Token head = {}; Token *cur = &head; for (; !tok->at_bol; tok = tok->next) { cur = cur->next = copy_token(tok); } cur->next = new_eof(tok); *rest = tok; return head.next; } static Token *new_num_token(int val, Token *tmpl) { char *p, *buf; p = buf = malloc(13); p = FormatInt32(p, val); p[0] = '\n'; p[1] = 0; return tokenize(new_file(tmpl->file->name, tmpl->file->file_no, buf)); } static Token *read_const_expr(Token **rest, Token *tok) { tok = copy_line(rest, tok); Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // "defined(foo)" or "defined foo" becomes "1" if macro "foo" // is defined. Otherwise "0". if (EQUAL(tok, "defined")) { Token *start = tok; bool has_paren = CONSUME(&tok, tok->next, "("); if (tok->kind != TK_IDENT) error_tok(start, "macro name must be an identifier"); Macro *m = find_macro(tok); tok = tok->next; if (has_paren) tok = skip(tok, ')'); cur = cur->next = new_num_token(m ? 1 : 0, start); continue; } cur = cur->next = tok; tok = tok->next; } cur->next = tok; return head.next; } // Read and evaluate a constant expression. static long eval_const_expr(Token **rest, Token *tok) { __arena_push(); Token *start = tok; Token *expr = read_const_expr(rest, tok->next); expr = preprocess2(expr); if (expr->kind == TK_EOF) error_tok(start, "no expression"); // [https://www.sigbus.info/n1570#6.10.1p4] The standard requires // we replace remaining non-macro identifiers with "0" before // evaluating a constant expression. For example, `#if foo` is // equivalent to `#if 0` if foo is not defined. for (Token *t = expr; t->kind != TK_EOF; t = t->next) { if (t->kind == TK_IDENT) { Token *next = t->next; *t = *new_num_token(0, t); t->next = next; } } // Convert pp-numbers to regular numbers convert_pp_tokens(expr); Token *rest2; long val = const_expr(&rest2, expr); if (rest2->kind != TK_EOF && rest2->kind != TK_JAVADOWN) { error_tok(rest2, "extra token"); } __arena_pop(); return val; } static CondIncl *push_cond_incl(Token *tok, bool included) { CondIncl *ci = calloc(1, sizeof(CondIncl)); ci->next = cond_incl; ci->ctx = IN_THEN; ci->tok = tok; ci->included = included; cond_incl = ci; return ci; } static Macro *find_macro(Token *tok) { if (tok->kind != TK_IDENT) return NULL; return hashmap_get2(&macros, tok->loc, tok->len); } static Macro *add_macro(char *name, bool is_objlike, Token *body) { Macro *m = calloc(1, sizeof(Macro)); m->name = name; m->is_objlike = is_objlike; m->body = body; hashmap_put(&macros, name, m); return m; } static MacroParam *read_macro_params(Token **rest, Token *tok, char **va_args_name) { MacroParam head = {}; MacroParam *cur = &head; while (!EQUAL(tok, ")")) { if (cur != &head) tok = skip(tok, ','); if (EQUAL(tok, "...")) { *va_args_name = "__VA_ARGS__"; *rest = skip(tok->next, ')'); return head.next; } if (tok->kind == TK_JAVADOWN) { tok = tok->next; } if (tok->kind != TK_IDENT) { error_tok(tok, "expected an identifier"); } if (EQUAL(tok->next, "...")) { *va_args_name = strndup(tok->loc, tok->len); *rest = skip(tok->next->next, ')'); return head.next; } MacroParam *m = calloc(1, sizeof(MacroParam)); m->name = strndup(tok->loc, tok->len); cur = cur->next = m; tok = tok->next; } *rest = tok->next; return head.next; } static Macro *read_macro_definition(Token **rest, Token *tok) { Macro *m; char *name; if (tok->kind != TK_IDENT) error_tok(tok, "macro name must be an identifier"); name = strndup(tok->loc, tok->len); tok = tok->next; if (!tok->has_space && tok->len == 1 && tok->loc[0] == '(') { // Function-like macro char *va_args_name = NULL; MacroParam *params = read_macro_params(&tok, tok->next, &va_args_name); m = add_macro(name, false, copy_line(rest, tok)); m->params = params; m->va_args_name = va_args_name; } else { // Object-like macro m = add_macro(name, true, copy_line(rest, tok)); } return m; } static MacroArg *read_macro_arg_one(Token **rest, Token *tok, bool read_rest) { Token head = {}; Token *cur = &head; int level = 0; for (;;) { if (level == 0 && tok->len == 1 && tok->loc[0] == ')') { break; } if (level == 0 && !read_rest && tok->len == 1 && tok->loc[0] == ',') { break; } if (tok->kind == TK_EOF) error_tok(tok, "premature end of input"); if (tok->len == 1 && tok->loc[0] == '(') { level++; } else if (tok->len == 1 && tok->loc[0] == ')') { level--; } cur = cur->next = copy_token(tok); tok = tok->next; } cur->next = new_eof(tok); MacroArg *arg = calloc(1, sizeof(MacroArg)); arg->tok = head.next; *rest = tok; return arg; } static MacroArg *read_macro_args(Token **rest, Token *tok, MacroParam *params, char *va_args_name) { Token *start = tok; tok = tok->next->next; MacroArg head = {}; MacroArg *cur = &head; MacroParam *pp = params; for (; pp; pp = pp->next) { if (cur != &head) tok = skip(tok, ','); cur = cur->next = read_macro_arg_one(&tok, tok, false); cur->name = pp->name; } if (va_args_name) { MacroArg *arg; if (tok->len == 1 && tok->loc[0] == ')') { arg = calloc(1, sizeof(MacroArg)); arg->tok = new_eof(tok); } else { if (pp != params) tok = skip(tok, ','); arg = read_macro_arg_one(&tok, tok, true); } arg->name = va_args_name; arg->is_va_args = true; cur = cur->next = arg; } else if (pp) { error_tok(start, "too many arguments"); } skip(tok, ')'); *rest = tok; return head.next; } static MacroArg *find_arg(MacroArg *args, Token *tok) { for (MacroArg *ap = args; ap; ap = ap->next) { if (tok->len == strlen(ap->name) && !strncmp(tok->loc, ap->name, tok->len)) { return ap; } } return NULL; } // Concatenates all tokens in `tok` and returns a new string. static char *join_tokens(Token *tok, Token *end) { // Compute the length of the resulting token. int len = 1; for (Token *t = tok; t != end && t->kind != TK_EOF; t = t->next) { if (t != tok && t->has_space) len++; len += t->len; } char *buf = calloc(1, len); // Copy token texts. int pos = 0; for (Token *t = tok; t != end && t->kind != TK_EOF; t = t->next) { if (t != tok && t->has_space) buf[pos++] = ' '; strncpy(buf + pos, t->loc, t->len); pos += t->len; } buf[pos] = '\0'; return buf; } // Concatenates all tokens in `arg` and returns a new string token. // This function is used for the stringizing operator (#). static Token *stringize(Token *hash, Token *arg) { // Create a new string token. We need to set some value to its // source location for error reporting function, so we use a macro // name token as a template. char *s = join_tokens(arg, NULL); return new_str_token(s, hash); } // Concatenate two tokens to create a new token. static Token *paste(Token *lhs, Token *rhs) { // Paste the two tokens. char *buf = xasprintf("%.*s%.*s", lhs->len, lhs->loc, rhs->len, rhs->loc); // Tokenize the resulting string. Token *tok = tokenize(new_file(lhs->file->name, lhs->file->file_no, buf)); if (tok->next->kind != TK_EOF) error_tok(lhs, "pasting forms '%s', an invalid token", buf); return tok; } static bool has_varargs(MacroArg *args) { for (MacroArg *ap = args; ap; ap = ap->next) { if (!strcmp(ap->name, "__VA_ARGS__")) { return ap->tok->kind != TK_EOF; } } return false; } // Replace func-like macro parameters with given arguments. static Token *subst(Token *tok, MacroArg *args) { Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // "#" followed by a parameter is replaced with stringized actuals. if (tok->len == 1 && tok->loc[0] == '#') { MacroArg *arg = find_arg(args, tok->next); if (!arg) { error_tok(tok->next, "'#' is not followed by a macro parameter"); } cur = cur->next = stringize(tok, arg->tok); tok = tok->next->next; continue; } // [GNU] If __VA_ARG__ is empty, `,##__VA_ARGS__` is expanded // to the empty token list. Otherwise, its expaned to `,` and // __VA_ARGS__. if (tok->len == 1 && tok->loc[0] == ',' && (tok->next->len == 2 && (tok->next->loc[0] == '#' && tok->next->loc[1] == '#'))) { MacroArg *arg = find_arg(args, tok->next->next); if (arg && arg->is_va_args) { if (arg->tok->kind == TK_EOF) { tok = tok->next->next->next; } else { cur = cur->next = copy_token(tok); tok = tok->next->next; } continue; } } if (tok->len == 2 && tok->loc[0] == '#' && tok->loc[1] == '#') { if (cur == &head) error_tok(tok, "'##' cannot appear at start of macro expansion"); if (tok->next->kind == TK_EOF) error_tok(tok, "'##' cannot appear at end of macro expansion"); MacroArg *arg = find_arg(args, tok->next); if (arg) { if (arg->tok->kind != TK_EOF) { *cur = *paste(cur, arg->tok); for (Token *t = arg->tok->next; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); } tok = tok->next->next; continue; } *cur = *paste(cur, tok->next); tok = tok->next->next; continue; } MacroArg *arg = find_arg(args, tok); if (arg && (tok->next->len == 2 && (tok->next->loc[0] == '#' && tok->next->loc[1] == '#'))) { Token *rhs = tok->next->next; if (arg->tok->kind == TK_EOF) { MacroArg *arg2 = find_arg(args, rhs); if (arg2) { for (Token *t = arg2->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); } else { cur = cur->next = copy_token(rhs); } tok = rhs->next; continue; } for (Token *t = arg->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); tok = tok->next; continue; } // If __VA_ARG__ is empty, __VA_OPT__(x) is expanded to the // empty token list. Otherwise, __VA_OPT__(x) is expanded to x. if (EQUAL(tok, "__VA_OPT__") && EQUAL(tok->next, "(")) { MacroArg *arg = read_macro_arg_one(&tok, tok->next->next, true); if (has_varargs(args)) for (Token *t = arg->tok; t->kind != TK_EOF; t = t->next) cur = cur->next = t; tok = skip(tok, ')'); continue; } // Handle a macro token. Macro arguments are completely macro-expanded // before they are substituted into a macro body. if (arg) { Token *t = preprocess2(arg->tok); t->at_bol = tok->at_bol; t->has_space = tok->has_space; for (; t->kind != TK_EOF; t = t->next) cur = cur->next = copy_token(t); tok = tok->next; continue; } // Handle a non-macro token. cur = cur->next = copy_token(tok); tok = tok->next; continue; } cur->next = tok; return head.next; } // If tok is a macro, expand it and return true. // Otherwise, do nothing and return false. static bool expand_macro(Token **rest, Token *tok) { if (hideset_contains(tok->hideset, tok->loc, tok->len)) return false; Macro *m = find_macro(tok); if (!m) return false; // Built-in dynamic macro application such as __LINE__ if (m->handler) { *rest = m->handler(tok); (*rest)->next = tok->next; return true; } // Object-like macro application if (m->is_objlike) { Hideset *hs = hideset_union(tok->hideset, new_hideset(m->name)); Token *body = add_hideset(m->body, hs); for (Token *t = body; t->kind != TK_EOF; t = t->next) { t->origin = tok; } *rest = append(body, tok->next); (*rest)->at_bol = tok->at_bol; (*rest)->has_space = tok->has_space; return true; } // If a funclike macro token is not followed by an argument list, // treat it as a normal identifier. if (!(tok->next->len == 1 && tok->next->loc[0] == '(')) return false; // Function-like macro application Token *macro_token = tok; MacroArg *args = read_macro_args(&tok, tok, m->params, m->va_args_name); Token *rparen = tok; // Tokens that consist a func-like macro invocation may have different // hidesets, and if that's the case, it's not clear what the hideset // for the new tokens should be. We take the interesection of the // macro token and the closing parenthesis and use it as a new hideset // as explained in the Dave Prossor's algorithm. Hideset *hs = hideset_intersection(macro_token->hideset, rparen->hideset); hs = hideset_union(hs, new_hideset(m->name)); Token *body = subst(m->body, args); body = add_hideset(body, hs); for (Token *t = body; t->kind != TK_EOF; t = t->next) t->origin = macro_token; *rest = append(body, tok->next); (*rest)->at_bol = macro_token->at_bol; (*rest)->has_space = macro_token->has_space; return true; } char *search_include_paths(char *filename) { if (filename[0] == '/') return filename; static HashMap cache; char *cached = hashmap_get(&cache, filename); if (cached) return cached; // Search a file from the include paths. for (int i = 0; i < include_paths.len; i++) { char *path = xasprintf("%s/%s", include_paths.data[i], filename); if (!fileexists(path)) continue; hashmap_put(&cache, filename, path); include_next_idx = i + 1; return path; } return NULL; } static char *search_include_next(char *filename) { for (; include_next_idx < include_paths.len; include_next_idx++) { char *path = xasprintf("%s/%s", include_paths.data[include_next_idx], filename); if (fileexists(path)) return path; } return NULL; } // Read an #include argument. static char *read_include_filename(Token **rest, Token *tok, bool *is_dquote) { // Pattern 1: #include "foo.h" if (tok->kind == TK_STR) { // A double-quoted filename for #include is a special kind of // token, and we don't want to interpret any escape sequences in it. // For example, "\f" in "C:\foo" is not a formfeed character but // just two non-control characters, backslash and f. // So we don't want to use token->str. *is_dquote = true; *rest = skip_line(tok->next); return strndup(tok->loc + 1, tok->len - 2); } // Pattern 2: #include <foo.h> if (EQUAL(tok, "<")) { // Reconstruct a filename from a sequence of tokens between // "<" and ">". Token *start = tok; // Find closing ">". for (; !EQUAL(tok, ">"); tok = tok->next) if (tok->at_bol || tok->kind == TK_EOF) error_tok(tok, "expected '>'"); *is_dquote = false; *rest = skip_line(tok->next); return join_tokens(start->next, tok); } // Pattern 3: #include FOO // In this case FOO must be macro-expanded to either // a single string token or a sequence of "<" ... ">". if (tok->kind == TK_IDENT) { Token *tok2 = preprocess2(copy_line(rest, tok)); return read_include_filename(&tok2, tok2, is_dquote); } error_tok(tok, "expected a filename"); } // Detect the following "include guard" pattern. // // #ifndef FOO_H // #define FOO_H // ... // #endif static char *detect_include_guard(Token *tok) { // Detect the first two lines. if (!is_hash(tok) || !EQUAL(tok->next, "ifndef")) return NULL; tok = tok->next->next; if (tok->kind != TK_IDENT) return NULL; char *macro = strndup(tok->loc, tok->len); tok = tok->next; if (!is_hash(tok) || !EQUAL(tok->next, "define") || !equal(tok->next->next, macro, strlen(macro))) return NULL; // Read until the end of the file. while (tok->kind != TK_EOF) { if (!is_hash(tok)) { tok = tok->next; continue; } if (EQUAL(tok->next, "endif") && tok->next->next->kind == TK_EOF) return macro; if (EQUAL(tok, "if") || EQUAL(tok, "ifdef") || EQUAL(tok, "ifndef")) tok = skip_cond_incl(tok->next); else tok = tok->next; } return NULL; } static Token *include_file(Token *tok, char *path, Token *filename_tok) { // Check for "#pragma once" if (hashmap_get(&pragma_once, path)) return tok; // If we read the same file before, and if the file was guarded // by the usual #ifndef ... #endif pattern, we may be able to // skip the file without opening it. static HashMap include_guards; char *guard_name = hashmap_get(&include_guards, path); if (guard_name && hashmap_get(&macros, guard_name)) return tok; Token *tok2 = tokenize_file(path); if (!tok2) error_tok(filename_tok, "%s: cannot open file: %s", path, strerror(errno)); guard_name = detect_include_guard(tok2); if (guard_name) hashmap_put(&include_guards, path, guard_name); return append(tok2, tok); } // Read #line arguments static void read_line_marker(Token **rest, Token *tok) { // TODO: This is broken if file is different? See gperf codegen. Token *start = tok; tok = preprocess(copy_line(rest, tok)); if (tok->kind != TK_NUM || tok->ty->kind != TY_INT) error_tok(tok, "invalid line marker"); start->file->line_delta = tok->val - start->line_no; tok = tok->next; if (tok->kind == TK_EOF) return; if (tok->kind != TK_STR) error_tok(tok, "filename expected"); start->file->display_name = tok->str; } // Visit all tokens in `tok` while evaluating preprocessing // macros and directives. static Token *preprocess2(Token *tok) { unsigned char kw; Token head = {}; Token *cur = &head; while (tok->kind != TK_EOF) { // If it is a macro, expand it. if (expand_macro(&tok, tok)) continue; // make sure javadown is removed if it's for a macro definition if (tok->kind == TK_JAVADOWN && is_hash(tok->next) && EQUAL(tok->next->next, "define")) { read_macro_definition(&tok, tok->next->next->next)->javadown = tok; continue; } // Pass through if it is not a "#". if (!is_hash(tok)) { tok->line_delta = tok->file->line_delta; tok->filename = tok->file->display_name; cur = cur->next = tok; tok = tok->next; continue; } Token *start = tok; tok = tok->next; if ((kw = GetKw(tok->loc, tok->len))) { if (kw == KW_INCLUDE) { bool is_dquote; char *filename = read_include_filename(&tok, tok->next, &is_dquote); if (filename[0] != '/' && is_dquote) { char *tmp = strdup(start->file->name); char *path = xasprintf("%s/%s", dirname(tmp), filename); free(tmp); bool exists = fileexists(path); free(path); if (exists) { tok = include_file(tok, path, start->next->next); continue; } } char *path = search_include_paths(filename); tok = include_file(tok, path ? path : filename, start->next->next); continue; } if (kw == KW_INCLUDE_NEXT) { bool ignore; char *filename = read_include_filename(&tok, tok->next, &ignore); char *path = search_include_next(filename); tok = include_file(tok, path ? path : filename, start->next->next); continue; } if (kw == KW_DEFINE) { read_macro_definition(&tok, tok->next); continue; } if (kw == KW_UNDEF) { tok = tok->next; if (tok->kind != TK_IDENT) error_tok(tok, "macro name must be an identifier"); undef_macro(strndup(tok->loc, tok->len)); tok = skip_line(tok->next); continue; } if (kw == KW_IF) { long val = eval_const_expr(&tok, tok); push_cond_incl(start, val); if (!val) tok = skip_cond_incl(tok); continue; } if (kw == KW_IFDEF) { bool defined = find_macro(tok->next); push_cond_incl(tok, defined); tok = skip_line(tok->next->next); if (!defined) tok = skip_cond_incl(tok); continue; } if (kw == KW_IFNDEF) { bool defined = find_macro(tok->next); push_cond_incl(tok, !defined); tok = skip_line(tok->next->next); if (defined) tok = skip_cond_incl(tok); continue; } if (kw == KW_ELIF) { if (!cond_incl || cond_incl->ctx == IN_ELSE) error_tok(start, "stray #elif"); cond_incl->ctx = IN_ELIF; if (!cond_incl->included && eval_const_expr(&tok, tok)) cond_incl->included = true; else tok = skip_cond_incl(tok); continue; } if (kw == KW_ELSE) { if (!cond_incl || cond_incl->ctx == IN_ELSE) error_tok(start, "stray #else"); cond_incl->ctx = IN_ELSE; tok = skip_line(tok->next); if (cond_incl->included) tok = skip_cond_incl(tok); continue; } if (kw == KW_ENDIF) { if (!cond_incl) error_tok(start, "stray #endif"); cond_incl = cond_incl->next; tok = skip_line(tok->next); continue; } if (kw == KW_LINE) { read_line_marker(&tok, tok->next); continue; } } if (tok->kind == TK_PP_NUM) { read_line_marker(&tok, tok); continue; } if (kw == KW_PRAGMA && EQUAL(tok->next, "once")) { hashmap_put(&pragma_once, tok->file->name, (void *)1); tok = skip_line(tok->next->next); continue; } if (kw == KW_PRAGMA) { do { tok = tok->next; } while (!tok->at_bol); continue; } if (kw == KW_ERROR) { error_tok(tok, "error"); } // `#`-only line is legal. It's called a null directive. if (tok->at_bol) continue; error_tok(tok, "invalid preprocessor directive"); } cur->next = tok; return head.next; } void define_macro(char *name, char *buf) { Token *tok = tokenize(new_file("<built-in>", 1, buf)); add_macro(name, true, tok); } void undef_macro(char *name) { hashmap_delete(&macros, name); } static Macro *add_builtin(char *name, macro_handler_fn *fn) { Macro *m = add_macro(name, true, NULL); m->handler = fn; return m; } static Token *file_macro(Token *tmpl) { while (tmpl->origin) tmpl = tmpl->origin; return new_str_token(tmpl->file->display_name, tmpl); } static Token *line_macro(Token *tmpl) { while (tmpl->origin) tmpl = tmpl->origin; int i = tmpl->line_no + tmpl->file->line_delta; return new_num_token(i, tmpl); } // __COUNTER__ is expanded to serial values starting from 0. static Token *counter_macro(Token *tmpl) { static int i = 0; return new_num_token(i++, tmpl); } // __TIMESTAMP__ is expanded to a string describing the last // modification time of the current file. E.g. // "Fri Jul 24 01:32:50 2020" static Token *timestamp_macro(Token *tmpl) { struct stat st; if (stat(tmpl->file->name, &st) != 0) return new_str_token("??? ??? ?? ??:??:?? ????", tmpl); char buf[64]; ctime_r(&st.st_mtim.tv_sec, buf); buf[24] = '\0'; return new_str_token(buf, tmpl); } static Token *base_file_macro(Token *tmpl) { return new_str_token(base_file, tmpl); } // __DATE__ is expanded to the current date, e.g. "May 17 2020". static char *format_date(struct tm *tm) { return xasprintf("\"%s %2d %d\"", kMonthNameShort[tm->tm_mon], tm->tm_mday, tm->tm_year + 1900); } // __TIME__ is expanded to the current time, e.g. "13:34:03". static char *format_time(struct tm *tm) { return xasprintf("\"%02d:%02d:%02d\"", tm->tm_hour, tm->tm_min, tm->tm_sec); } void init_macros_conditional(void) { if (opt_pg) define_macro("__PG__", "1"); if (opt_pic) define_macro("__PIC__", "1"); if (opt_sse3) define_macro("__SSE3__", "1"); if (opt_sse4) define_macro("__SSE4__", "1"); if (opt_popcnt) define_macro("__POPCNT__", "1"); if (opt_fentry) define_macro("__MFENTRY__", "1"); } void init_macros(void) { char *val, *name = "\ __chibicc__\000\ 1\000\ __cosmopolitan__\000\ 1\000\ __GNUC__\000\ 9\000\ __GNUC_MINOR__\000\ 0\000\ __GNUC_PATCHLEVEL__\000\ 0\000\ __NO_INLINE__\000\ 16\000\ __GNUC_STDC_INLINE__\000\ 1\000\ __BIGGEST_ALIGNMENT__\000\ 16\000\ __C99_MACRO_WITH_VA_ARGS\000\ 1\000\ __GCC_ASM_FLAG_OUTPUTS__\000\ 1\000\ __ELF__\000\ 1\000\ __LP64__\000\ 1\000\ _LP64\000\ 1\000\ __STDC__\000\ 1\000\ __STDC_HOSTED__\000\ 1\000\ __STDC_NO_COMPLEX__\000\ 1\000\ __STDC_UTF_16__\000\ 1\000\ __STDC_UTF_32__\000\ 1\000\ __STDC_VERSION__\000\ 201112L\000\ __USER_LABEL_PREFIX__\000\ \000\ __alignof__\000\ _Alignof\000\ __const__\000\ const\000\ __inline__\000\ inline\000\ __signed__\000\ signed\000\ __typeof__\000\ typeof\000\ __volatile__\000\ volatile\000\ __unix\000\ 1\000\ __unix__\000\ 1\000\ __linux\000\ 1\000\ __linux__\000\ 1\000\ __gnu_linux__\000\ 1\000\ __BYTE_ORDER__\000\ 1234\000\ __FLOAT_WORD_ORDER__\000\ 1234\000\ __ORDER_BIG_ENDIAN__\000\ 4321\000\ __ORDER_LITTLE_ENDIAN__\000\ 1234\000\ __INT8_MAX__\000\ 0x7f\000\ __UINT8_MAX__\000\ 0xff\000\ __INT16_MAX__\000\ 0x7fff\000\ __UINT16_MAX__\000\ 0xffff\000\ __SHRT_MAX__\000\ 0x7fff\000\ __INT_MAX__\000\ 0x7fffffff\000\ __INT32_MAX__\000\ 0x7fffffff\000\ __UINT32_MAX__\000\ 0xffffffffu\000\ __INT64_MAX__\000\ 0x7fffffffffffffffl\000\ __INTMAX_MAX__\000\ 0x7fffffffffffffffl\000\ __LONG_MAX__\000\ 0x7fffffffffffffffl\000\ __LONG_LONG_MAX__\000\ 0x7fffffffffffffffl\000\ __UINT64_MAX__\000\ 0xfffffffffffffffful\000\ __UINTMAX_MAX__\000\ 0xfffffffffffffffful\000\ __SIZE_MAX__\000\ 0xfffffffffffffffful\000\ __INTPTR_MAX__\000\ 0x7fffffffffffffffl\000\ __UINTPTR_MAX__\000\ 0xfffffffffffffffful\000\ __WINT_MAX__\000\ 0xffffffffu\000\ __CHAR_BIT__\000\ 8\000\ __SIZEOF_SHORT__\000\ 2\000\ __SIZEOF_INT__\000\ 4\000\ __SIZEOF_LONG__\000\ 8\000\ __SIZEOF_LONG_LONG__\000\ 8\000\ __SIZEOF_POINTER__\000\ 8\000\ __SIZEOF_PTRDIFF_T__\000\ 8\000\ __SIZEOF_SIZE_T__\000\ 8\000\ __SIZEOF_WCHAR_T__\000\ 4\000\ __SIZEOF_WINT_T__\000\ 4\000\ __SIZEOF_FLOAT__\000\ 4\000\ __SIZEOF_FLOAT128__\000\ 16\000\ __SIZEOF_DOUBLE__\000\ 8\000\ __SIZEOF_FLOAT80__\000\ 16\000\ __SIZEOF_LONG_DOUBLE__\000\ 16\000\ __INT8_TYPE__\000\ signed char\000\ __UINT8_TYPE__\000\ unsigned char\000\ __INT16_TYPE__\000\ short int\000\ __UINT16_TYPE__\000\ short unsigned int\000\ __INT32_TYPE__\000\ int\000\ __UINT32_TYPE__\000\ unsigned int\000\ __INT64_TYPE__\000\ long int\000\ __INTMAX_TYPE__\000\ long int\000\ __UINT64_TYPE__\000\ long unsigned int\000\ __UINTMAX_TYPE__\000\ long unsigned int\000\ __INTMAX_TYPE__\000\ long int\000\ __UINTMAX_TYPE__\000\ long unsigned int\000\ __INTPTR_TYPE__\000\ long int\000\ __UINTPTR_TYPE__\000\ long unsigned int\000\ __PTRDIFF_TYPE__\000\ long int\000\ __SIZE_TYPE__\000\ long unsigned int\000\ __WCHAR_TYPE__\000\ int\000\ __CHAR16_TYPE__\000\ short unsigned int\000\ __CHAR32_TYPE__\000\ unsigned int\000\ __WINT_TYPE__\000\ unsigned int\000\ __CHAR16_TYPE__\000\ short unsigned int\000\ __WCHAR_TYPE__\000\ int\000\ __CHAR32_TYPE__\000\ unsigned int\000\ __INT_LEAST8_TYPE__\000\ signed char\000\ __UINT_LEAST8_TYPE__\000\ unsigned char\000\ __INT_LEAST16_TYPE__\000\ int\000\ __UINT_LEAST16_TYPE__\000\ unsigned short\000\ __INT_LEAST32_TYPE__\000\ short\000\ __UINT_LEAST32_TYPE__\000\ unsigned int\000\ __INT_LEAST64_TYPE__\000\ long\000\ __UINT_LEAST64_TYPE__\000\ unsigned long\000\ __INT_FAST8_TYPE__\000\ signed char\000\ __UINT_FAST8_TYPE__\000\ unsigned char\000\ __INT_FAST16_TYPE__\000\ int\000\ __UINT_FAST16_TYPE__\000\ unsigned\000\ __INT_FAST32_TYPE__\000\ int\000\ __UINT_FAST32_TYPE__\000\ unsigned\000\ __INT_FAST8_MAX__\000\ 0x7f\000\ __INT_FAST16_MAX__\000\ 0x7fffffff\000\ __INT_FAST32_MAX__\000\ 0x7fffffff\000\ __INT_FAST64_MAX__\000\ 0x7fffffffffffffffl\000\ __INT_FAST64_TYPE__\000\ long\000\ __UINT_FAST64_TYPE__\000\ unsigned long\000\ __DBL_DECIMAL_DIG__\000\ 17\000\ __DBL_DENORM_MIN__\000\ ((double)4.94065645841246544176568792868221372e-324L)\000\ __DBL_DIG__\000\ 15\000\ __DBL_EPSILON__\000\ ((double)2.22044604925031308084726333618164062e-16L)\000\ __DBL_HAS_DENORM__\000\ 1\000\ __DBL_HAS_INFINITY__\000\ 1\000\ __DBL_HAS_QUIET_NAN__\000\ 1\000\ __DBL_MANT_DIG__\000\ 53\000\ __DBL_MAX_10_EXP__\000\ 308\000\ __DBL_MAX_EXP__\000\ 1024\000\ __DBL_MAX__\000\ ((double)1.79769313486231570814527423731704357e+308L)\000\ __DBL_MIN_10_EXP__\000\ (-307)\000\ __DBL_MIN_EXP__\000\ (-1021)\000\ __DBL_MIN__\000\ ((double)2.22507385850720138309023271733240406e-308L)\000\ __FLT_DECIMAL_DIG__\000\ 9\000\ __FLT_DENORM_MIN__\000\ 1.40129846432481707092372958328991613e-45F\000\ __FLT_DIG__\000\ 6\000\ __FLT_EPSILON__\000\ 1.19209289550781250000000000000000000e-7F\000\ __FLT_EVAL_METHOD_TS_18661_3__\000\ 0\000\ __FLT_EVAL_METHOD__\000\ 0\000\ __FLT_HAS_DENORM__\000\ 1\000\ __FLT_HAS_INFINITY__\000\ 1\000\ __FLT_HAS_QUIET_NAN__\000\ 1\000\ __FLT_MANT_DIG__\000\ 24\000\ __FLT_MAX_10_EXP__\000\ 38\000\ __FLT_MAX_EXP__\000\ 128\000\ __FLT_MAX__\000\ 3.40282346638528859811704183484516925e+38F\000\ __FLT_MIN_10_EXP__\000\ (-37)\000\ __FLT_MIN_EXP__\000\ (-125)\000\ __FLT_MIN__\000\ 1.17549435082228750796873653722224568e-38F\000\ __FLT_RADIX__\000\ 2\000\ __LDBL_DECIMAL_DIG__\000\ 21\000\ __LDBL_DENORM_MIN__\000\ 3.64519953188247460252840593361941982e-4951L\000\ __LDBL_DIG__\000\ 18\000\ __LDBL_EPSILON__\000\ 1.08420217248550443400745280086994171e-19L\000\ __LDBL_HAS_DENORM__\000\ 1\000\ __LDBL_HAS_INFINITY__\000\ 1\000\ __LDBL_HAS_QUIET_NAN__\000\ 1\000\ __LDBL_MANT_DIG__\000\ 64\000\ __LDBL_MAX_10_EXP__\000\ 4932\000\ __LDBL_MAX_EXP__\000\ 16384\000\ __LDBL_MAX__\000\ 1.18973149535723176502126385303097021e+4932L\000\ __LDBL_MIN_10_EXP__\000\ (-4931)\000\ __LDBL_MIN_EXP__\000\ (-16381)\000\ __LDBL_MIN__\000\ 3.36210314311209350626267781732175260e-4932L\000\ __x86_64\000\ 1\000\ __x86_64__\000\ 1\000\ __amd64\000\ 1\000\ __amd64__\000\ 1\000\ __MMX__\000\ 1\000\ __SSE__\000\ 1\000\ __SSE_MATH__\000\ 1\000\ __SSE2__\000\ 1\000\ __SSE2_MATH__\000\ 1\000\ __ATOMIC_ACQUIRE\000\ 2\000\ __ATOMIC_HLE_RELEASE\000\ 131072\000\ __ATOMIC_HLE_ACQUIRE\000\ 65536\000\ __ATOMIC_RELAXED\000\ 0\000\ __ATOMIC_CONSUME\000\ 1\000\ __ATOMIC_SEQ_CST\000\ 5\000\ __ATOMIC_ACQ_REL\000\ 4\000\ __ATOMIC_RELEASE\000\ 3\000\ \000"; do { val = name + strlen(name) + 1; define_macro(name, val); name = val + strlen(val) + 1; } while (*name); add_builtin("__FILE__", file_macro); add_builtin("__LINE__", line_macro); add_builtin("__COUNTER__", counter_macro); add_builtin("__TIMESTAMP__", timestamp_macro); add_builtin("__BASE_FILE__", base_file_macro); time_t now = time(NULL); struct tm *tm = localtime(&now); define_macro("__DATE__", format_date(tm)); define_macro("__TIME__", format_time(tm)); } static StringKind getStringKind(Token *tok) { if (!strcmp(tok->loc, "u8")) return STR_UTF8; switch (tok->loc[0]) { case '"': return STR_NONE; case 'u': return STR_UTF16; case 'U': return STR_UTF32; case 'L': return STR_WIDE; } UNREACHABLE(); } // Concatenate adjacent string literals into a single string literal // as per the C spec. static void join_adjacent_string_literals(Token *tok) { // First pass: If regular string literals are adjacent to wide // string literals, regular string literals are converted to a wide // type before concatenation. In this pass, we do the conversion. for (Token *tok1 = tok; tok1->kind != TK_EOF;) { if (tok1->kind != TK_STR || tok1->next->kind != TK_STR) { tok1 = tok1->next; continue; } StringKind kind = getStringKind(tok1); Type *basety = tok1->ty->base; for (Token *t = tok1->next; t->kind == TK_STR; t = t->next) { StringKind k = getStringKind(t); if (kind == STR_NONE) { kind = k; basety = t->ty->base; } else if (k != STR_NONE && kind != k) { error_tok(t, "unsupported non-standard concatenation of string literals"); } } if (basety->size > 1) { for (Token *t = tok1; t->kind == TK_STR; t = t->next) { if (t->ty->base->size == 1) { *t = *tokenize_string_literal(t, basety); } } } while (tok1->kind == TK_STR) tok1 = tok1->next; } // Second pass: concatenate adjacent string literals. for (Token *tok1 = tok; tok1->kind != TK_EOF;) { if (tok1->kind != TK_STR || tok1->next->kind != TK_STR) { tok1 = tok1->next; continue; } Token *tok2 = tok1->next; while (tok2->kind == TK_STR) tok2 = tok2->next; int len = tok1->ty->array_len; for (Token *t = tok1->next; t != tok2; t = t->next) { len = len + t->ty->array_len - 1; } char *buf = calloc(tok1->ty->base->size, len); int j = 0; int i = 0; for (Token *t = tok1; t != tok2; t = t->next) { ++j; memcpy(buf + i, t->str, t->ty->size); i = i + t->ty->size - t->ty->base->size; } *tok1 = *copy_token(tok1); tok1->ty = array_of(tok1->ty->base, len); tok1->str = buf; tok1->next = tok2; tok1 = tok2; } } // Entry point function of the preprocessor. Token *preprocess(Token *tok) { tok = preprocess2(tok); if (cond_incl) { error_tok(cond_incl->tok, "unterminated conditional directive"); } convert_pp_tokens(tok); join_adjacent_string_literals(tok); for (Token *t = tok; t; t = t->next) { t->line_no += t->line_delta; } return tok; }
27.574753
80
0.631595
[ "object" ]
a5b7b14ab765f2531192a7d3ae763ecea0a2b322
1,628
c
C
obj_process_face_triangle.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
null
null
null
obj_process_face_triangle.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
1
2019-11-01T09:10:33.000Z
2019-11-01T09:10:33.000Z
obj_process_face_triangle.c
tac4ttack/simpleOBJ
7aaaa2424ca04d5cf8502cb849392fb7ddff2659
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* obj_process_face_triangle.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fmessina <fmessina@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/28 15:42:33 by fmessina #+# #+# */ /* Updated: 2019/07/01 16:46:38 by fmessina ### ########.fr */ /* */ /* ************************************************************************** */ #include "simple_obj.h" bool obj_process_face_triangle(t_obj *obj, char **split, int index) { int i; int mod; bool fail; if (obj && split && !(fail = false)) { i = 0; if ((mod = obj_process_face_type_get(*split)) == -1) return (obj_berror("Invalid face element type!\n", NULL)); while (i++ < 3) { if (mod != obj_process_face_type_get(*split)) return (obj_berror("Face element type has changed!\n", NULL)); fail = !obj_process_face_data_dispatch(obj, *split, mod, index); if (fail) return (obj_berror("Failed to retrieve face data!\n", NULL)); index += 3; split++; } return (true); } return (obj_berror("[ERROR obj_process_face_triangle]\t" \ "NULL mesh or split pointer!\n", NULL)); }
39.707317
80
0.364251
[ "mesh" ]
a5b86c489b6aee4580e14aa43937d013738e7610
1,688
h
C
elreader/src/I2CLCD16x2/i2clcd16x2.h
Hguimaraes/el-reader
aa711bbd7f1a4107cffa5c9f0ebb85270b9a0e80
[ "MIT" ]
null
null
null
elreader/src/I2CLCD16x2/i2clcd16x2.h
Hguimaraes/el-reader
aa711bbd7f1a4107cffa5c9f0ebb85270b9a0e80
[ "MIT" ]
null
null
null
elreader/src/I2CLCD16x2/i2clcd16x2.h
Hguimaraes/el-reader
aa711bbd7f1a4107cffa5c9f0ebb85270b9a0e80
[ "MIT" ]
null
null
null
/** ** @file i2clcd16x2.h ** @class I2CLCD16x2 ** @Description: ** This file contains a specific implementation to use the ** LCD 16x2 with I2C on NodeMCU. It's a simple wrapper of the ** LiquidCrystal_I2C library with functions useful for our application. **/ #ifndef _I2CLCD16X2_H #define _I2CLCD16X2_H #include "Arduino.h" #include "LiquidCrystal_I2C.h" namespace EasyLab{ class I2CLCD16x2 { private: // Custom character to print the degree symbol in the LCD byte degreeChar[8] = {0b00111, 0b00101, 0b00111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000}; // Create an object of LiquidCrystal_I2C library to manipulate // the LCD. This is the original library to manipulate LCD with I2C // I2CLCD16x2 is only a wrapper around this class, for a specific domain problem LiquidCrystal_I2C *lcd; // I2C Address of the display uint8_t lcd_address; public: // Constructor and destructor of the Class. To instatiate an I2CLCD16x2 // object we only need the I2C address in uint8_t. For NodeMCU is likely to // be 0x3F. To discover your port you can follow these steps of [1]. // @Reference: // [1] - http://playground.arduino.cc/Main/I2cScanner I2CLCD16x2(uint8_t lcd_address); virtual ~I2CLCD16x2(); // Public method to write the temperature (internal and external) values // in the LCD. void WriteTemperature(float in, float ext); // Public method to write the IP of the device on the display void WriteIPAddress(String IP); // Getter and setter for lcd_address void setLCDAddress(uint8_t lcd_address); uint8_t getLCDAddress(); }; } #endif
31.259259
84
0.69846
[ "object" ]
a5b9b6cdb470b8724f4a185d2ffb170789255be0
543,468
c
C
src/H5Shyper.c
alessandrofelder/hdf5
131402a92de9bbd5df60d5859c37c4820c60d6b9
[ "BSD-3-Clause-LBNL" ]
3
2020-10-23T12:56:24.000Z
2021-10-21T05:59:41.000Z
src/H5Shyper.c
alessandrofelder/hdf5
131402a92de9bbd5df60d5859c37c4820c60d6b9
[ "BSD-3-Clause-LBNL" ]
3
2021-06-07T15:59:49.000Z
2021-11-03T16:56:07.000Z
src/H5Shyper.c
alessandrofelder/hdf5
131402a92de9bbd5df60d5859c37c4820c60d6b9
[ "BSD-3-Clause-LBNL" ]
3
2020-11-06T16:08:38.000Z
2021-05-24T17:58:46.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the COPYING file, which can be found at the root of the source code * * distribution tree, or in https://www.hdfgroup.org/licenses. * * If you do not have access to either file, you may request a copy from * * help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Programmer: Quincey Koziol * Thursday, June 18, 1998 * * Purpose: Hyperslab selection dataspace I/O functions. */ /****************/ /* Module Setup */ /****************/ #include "H5Smodule.h" /* This source code file is part of the H5S module */ /***********/ /* Headers */ /***********/ #include "H5private.h" /* Generic Functions */ #include "H5CXprivate.h" /* API Contexts */ #include "H5Eprivate.h" /* Error handling */ #include "H5FLprivate.h" /* Free Lists */ #include "H5Iprivate.h" /* ID Functions */ #include "H5MMprivate.h" /* Memory management */ #include "H5Spkg.h" /* Dataspace functions */ #include "H5VMprivate.h" /* Vector functions */ /****************/ /* Local Macros */ /****************/ /* Flags for which hyperslab fragments to compute */ #define H5S_HYPER_COMPUTE_B_NOT_A 0x01 #define H5S_HYPER_COMPUTE_A_AND_B 0x02 #define H5S_HYPER_COMPUTE_A_NOT_B 0x04 /* Macro to advance a span, possibly recycling it first */ #define H5S_HYPER_ADVANCE_SPAN(recover, curr_span, next_span) \ do { \ H5S_hyper_span_t *saved_next_span = (next_span); \ \ /* Check if the span should be recovered */ \ if (recover) { \ H5S__hyper_free_span(curr_span); \ (recover) = FALSE; \ } /* end if */ \ \ /* Set the current span to saved next span */ \ (curr_span) = saved_next_span; \ } while (0) /* Macro to add "skipped" elements to projection during the execution of * H5S__hyper_project_intersect() */ #define H5S_HYPER_PROJ_INT_ADD_SKIP(UDATA, ADD, ERR) \ do { \ /* If there are any elements to add, we must add them \ * to the projection first before adding skip */ \ if ((UDATA)->nelem > 0) \ if (H5S__hyper_proj_int_build_proj(UDATA) < 0) \ HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, ERR, "can't add elements to projected selection") \ (UDATA)->skip += (ADD); \ } while (0) /* end H5S_HYPER_PROJ_INT_ADD_SKIP() */ /******************/ /* Local Typedefs */ /******************/ /* Define alias for hsize_t, for allocating H5S_hyper_span_info_t + bounds objects */ /* (Makes it easier to understand the alloc / free calls) */ typedef hsize_t hbounds_t; /* Struct for holding persistent information during iteration for * H5S__hyper_project_intersect() */ typedef struct { const H5S_hyper_span_t * ds_span[H5S_MAX_RANK]; /* Array of the current spans in the destination space in each dimension */ hsize_t ds_low[H5S_MAX_RANK]; /* Array of current low bounds (of iteration) for each element in ds_span */ H5S_hyper_span_info_t * ps_span_info[H5S_MAX_RANK]; /* Array of span info structs for projected space during iteration */ uint32_t ps_clean_bitmap; /* Bitmap of whether the nth rank has a clean projected space since the last time it was set to 1 */ unsigned ss_rank; /* Rank of source space */ unsigned ds_rank; /* Rank of destination space */ unsigned depth; /* Current depth of iterator in destination space */ hsize_t skip; /* Number of elements to skip in projected space */ hsize_t nelem; /* Number of elements to add to projected space (after skip) */ uint64_t op_gen; /* Operation generation for counting elements */ hbool_t share_selection; /* Whether span trees in dst_space can be shared with proj_space */ } H5S_hyper_project_intersect_ud_t; /* Assert that H5S_MAX_RANK is <= 32 so our trick with using a 32 bit bitmap * (ps_clean_bitmap) works. If H5S_MAX_RANK increases either increase the size * of ps_clean_bitmap or change the algorithm to use an array. */ #if H5S_MAX_RANK > 32 #error H5S_MAX_RANK too large for ps_clean_bitmap field in H5S_hyper_project_intersect_ud_t struct #endif /********************/ /* Local Prototypes */ /********************/ static H5S_hyper_span_t * H5S__hyper_new_span(hsize_t low, hsize_t high, H5S_hyper_span_info_t *down, H5S_hyper_span_t *next); static H5S_hyper_span_info_t *H5S__hyper_new_span_info(unsigned rank); static H5S_hyper_span_info_t *H5S__hyper_copy_span_helper(H5S_hyper_span_info_t *spans, unsigned rank, unsigned op_info_i, uint64_t op_gen); static H5S_hyper_span_info_t *H5S__hyper_copy_span(H5S_hyper_span_info_t *spans, unsigned rank); static hbool_t H5S__hyper_cmp_spans(const H5S_hyper_span_info_t *span_info1, const H5S_hyper_span_info_t *span_info2); static void H5S__hyper_free_span_info(H5S_hyper_span_info_t *span_info); static void H5S__hyper_free_span(H5S_hyper_span_t *span); static herr_t H5S__hyper_span_blocklist(const H5S_hyper_span_info_t *spans, hsize_t start[], hsize_t end[], hsize_t rank, hsize_t *startblock, hsize_t *numblocks, hsize_t **buf); static herr_t H5S__get_select_hyper_blocklist(H5S_t *space, hsize_t startblock, hsize_t numblocks, hsize_t *buf); static H5S_hyper_span_t *H5S__hyper_coord_to_span(unsigned rank, const hsize_t *coords); static herr_t H5S__hyper_append_span(H5S_hyper_span_info_t **span_tree, unsigned ndims, hsize_t low, hsize_t high, H5S_hyper_span_info_t *down); static herr_t H5S__hyper_clip_spans(H5S_hyper_span_info_t *a_spans, H5S_hyper_span_info_t *b_spans, unsigned selector, unsigned ndims, H5S_hyper_span_info_t **a_not_b, H5S_hyper_span_info_t **a_and_b, H5S_hyper_span_info_t **b_not_a); static herr_t H5S__hyper_merge_spans(H5S_t *space, H5S_hyper_span_info_t *new_spans); static hsize_t H5S__hyper_spans_nelem_helper(H5S_hyper_span_info_t *spans, unsigned op_info_i, uint64_t op_gen); static hsize_t H5S__hyper_spans_nelem(H5S_hyper_span_info_t *spans); static herr_t H5S__hyper_add_disjoint_spans(H5S_t *space, H5S_hyper_span_info_t *new_spans); static H5S_hyper_span_info_t *H5S__hyper_make_spans(unsigned rank, const hsize_t *start, const hsize_t *stride, const hsize_t *count, const hsize_t *block); static herr_t H5S__hyper_update_diminfo(H5S_t *space, H5S_seloper_t op, const H5S_hyper_dim_t *new_hyper_diminfo); static herr_t H5S__hyper_generate_spans(H5S_t *space); static hbool_t H5S__check_spans_overlap(const H5S_hyper_span_info_t *spans1, const H5S_hyper_span_info_t *spans2); static herr_t H5S__fill_in_new_space(H5S_t *space1, H5S_seloper_t op, H5S_hyper_span_info_t *space2_span_lst, hbool_t can_own_span2, hbool_t *span2_owned, hbool_t *updated_spans, H5S_t **result); static herr_t H5S__generate_hyperslab(H5S_t *space, H5S_seloper_t op, const hsize_t start[], const hsize_t stride[], const hsize_t count[], const hsize_t block[]); static herr_t H5S__set_regular_hyperslab(H5S_t *space, const hsize_t start[], const hsize_t *app_stride, const hsize_t app_count[], const hsize_t *app_block, const hsize_t *opt_stride, const hsize_t opt_count[], const hsize_t *opt_block); static herr_t H5S__fill_in_select(H5S_t *space1, H5S_seloper_t op, H5S_t *space2, H5S_t **result); static H5S_t * H5S__combine_select(H5S_t *space1, H5S_seloper_t op, H5S_t *space2); static herr_t H5S__hyper_iter_get_seq_list_gen(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len); static herr_t H5S__hyper_iter_get_seq_list_opt(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len); static herr_t H5S__hyper_iter_get_seq_list_single(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len); static herr_t H5S__hyper_proj_int_build_proj(H5S_hyper_project_intersect_ud_t *udata); static herr_t H5S__hyper_proj_int_iterate(const H5S_hyper_span_info_t *ss_span_info, const H5S_hyper_span_info_t *sis_span_info, hsize_t count, unsigned depth, H5S_hyper_project_intersect_ud_t *udata); static void H5S__hyper_get_clip_diminfo(hsize_t start, hsize_t stride, hsize_t *count, hsize_t *block, hsize_t clip_size); static hsize_t H5S__hyper_get_clip_extent_real(const H5S_t *clip_space, hsize_t num_slices, hbool_t incl_trail); /* Selection callbacks */ static herr_t H5S__hyper_copy(H5S_t *dst, const H5S_t *src, hbool_t share_selection); static herr_t H5S__hyper_release(H5S_t *space); static htri_t H5S__hyper_is_valid(const H5S_t *space); static hsize_t H5S__hyper_span_nblocks(H5S_hyper_span_info_t *spans); static hssize_t H5S__hyper_serial_size(const H5S_t *space); static herr_t H5S__hyper_serialize(const H5S_t *space, uint8_t **p); static herr_t H5S__hyper_deserialize(H5S_t **space, const uint8_t **p); static herr_t H5S__hyper_bounds(const H5S_t *space, hsize_t *start, hsize_t *end); static herr_t H5S__hyper_offset(const H5S_t *space, hsize_t *offset); static int H5S__hyper_unlim_dim(const H5S_t *space); static herr_t H5S__hyper_num_elem_non_unlim(const H5S_t *space, hsize_t *num_elem_non_unlim); static htri_t H5S__hyper_is_contiguous(const H5S_t *space); static htri_t H5S__hyper_is_single(const H5S_t *space); static htri_t H5S__hyper_is_regular(const H5S_t *space); static htri_t H5S__hyper_shape_same(const H5S_t *space1, const H5S_t *space2); static htri_t H5S__hyper_intersect_block(const H5S_t *space, const hsize_t *start, const hsize_t *end); static herr_t H5S__hyper_adjust_u(H5S_t *space, const hsize_t *offset); static herr_t H5S__hyper_adjust_s(H5S_t *space, const hssize_t *offset); static herr_t H5S__hyper_project_scalar(const H5S_t *space, hsize_t *offset); static herr_t H5S__hyper_project_simple(const H5S_t *space, H5S_t *new_space, hsize_t *offset); static herr_t H5S__hyper_iter_init(const H5S_t *space, H5S_sel_iter_t *iter); /* Selection iteration callbacks */ static herr_t H5S__hyper_iter_coords(const H5S_sel_iter_t *iter, hsize_t *coords); static herr_t H5S__hyper_iter_block(const H5S_sel_iter_t *iter, hsize_t *start, hsize_t *end); static hsize_t H5S__hyper_iter_nelmts(const H5S_sel_iter_t *iter); static htri_t H5S__hyper_iter_has_next_block(const H5S_sel_iter_t *sel_iter); static herr_t H5S__hyper_iter_next(H5S_sel_iter_t *sel_iter, size_t nelem); static herr_t H5S__hyper_iter_next_block(H5S_sel_iter_t *sel_iter); static herr_t H5S__hyper_iter_get_seq_list(H5S_sel_iter_t *iter, size_t maxseq, size_t maxbytes, size_t *nseq, size_t *nbytes, hsize_t *off, size_t *len); static herr_t H5S__hyper_iter_release(H5S_sel_iter_t *sel_iter); /*****************************/ /* Library Private Variables */ /*****************************/ /*********************/ /* Package Variables */ /*********************/ /* Selection properties for hyperslab selections */ const H5S_select_class_t H5S_sel_hyper[1] = {{ H5S_SEL_HYPERSLABS, /* Methods on selection */ H5S__hyper_copy, H5S__hyper_release, H5S__hyper_is_valid, H5S__hyper_serial_size, H5S__hyper_serialize, H5S__hyper_deserialize, H5S__hyper_bounds, H5S__hyper_offset, H5S__hyper_unlim_dim, H5S__hyper_num_elem_non_unlim, H5S__hyper_is_contiguous, H5S__hyper_is_single, H5S__hyper_is_regular, H5S__hyper_shape_same, H5S__hyper_intersect_block, H5S__hyper_adjust_u, H5S__hyper_adjust_s, H5S__hyper_project_scalar, H5S__hyper_project_simple, H5S__hyper_iter_init, }}; /* Format version bounds for dataspace hyperslab selection */ const unsigned H5O_sds_hyper_ver_bounds[] = { H5S_HYPER_VERSION_1, /* H5F_LIBVER_EARLIEST */ H5S_HYPER_VERSION_1, /* H5F_LIBVER_V18 */ H5S_HYPER_VERSION_2, /* H5F_LIBVER_V110 */ H5S_HYPER_VERSION_3, /* H5F_LIBVER_V112 */ H5S_HYPER_VERSION_3 /* H5F_LIBVER_LATEST */ }; /*******************/ /* Local Variables */ /*******************/ /* Iteration properties for hyperslab selections */ static const H5S_sel_iter_class_t H5S_sel_iter_hyper[1] = {{ H5S_SEL_HYPERSLABS, /* Methods on selection iterator */ H5S__hyper_iter_coords, H5S__hyper_iter_block, H5S__hyper_iter_nelmts, H5S__hyper_iter_has_next_block, H5S__hyper_iter_next, H5S__hyper_iter_next_block, H5S__hyper_iter_get_seq_list, H5S__hyper_iter_release, }}; /* Arrays for default stride, block, etc. */ static const hsize_t H5S_hyper_zeros_g[H5S_MAX_RANK] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static const hsize_t H5S_hyper_ones_g[H5S_MAX_RANK] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; /* Declare a free list to manage the H5S_hyper_sel_t struct */ H5FL_DEFINE_STATIC(H5S_hyper_sel_t); /* Declare a free list to manage the H5S_hyper_span_t struct */ H5FL_DEFINE_STATIC(H5S_hyper_span_t); /* Declare a free list to manage the H5S_hyper_span_info_t + hsize_t array struct */ H5FL_BARR_DEFINE_STATIC(H5S_hyper_span_info_t, hbounds_t, H5S_MAX_RANK * 2); /* Declare extern free list to manage the H5S_sel_iter_t struct */ H5FL_EXTERN(H5S_sel_iter_t); /* Current operation generation */ /* (Start with '1' to avoid clashing with '0' value in newly allocated structs) */ static uint64_t H5S_hyper_op_gen_g = 1; /* Uncomment this to provide the debugging routines for printing selection info */ /* #define H5S_HYPER_DEBUG */ #ifdef H5S_HYPER_DEBUG static herr_t H5S__hyper_print_spans_helper(FILE *f, const H5S_hyper_span_t *span, unsigned depth) { FUNC_ENTER_STATIC_NOERR while (span) { HDfprintf(f, "%s: %*sdepth=%u, span=%p, (%Hu, %Hu), next=%p\n", __func__, depth * 2, "", depth, span, span->low, span->high, span->next); if (span->down) { HDfprintf(f, "%s: %*sspans=%p, count=%u, bounds[0]={%Hu, %Hu}, head=%p\n", __func__, (depth + 1) * 2, "", span->down, span->down->count, span->down->low_bounds[0], span->down->high_bounds[0], span->down->head); H5S__hyper_print_spans_helper(f, span->down->head, depth + 1); } /* end if */ span = span->next; } /* end while */ FUNC_LEAVE_NOAPI(SUCCEED) } static herr_t H5S__hyper_print_spans(FILE *f, const H5S_hyper_span_info_t *span_lst) { FUNC_ENTER_STATIC_NOERR if (span_lst != NULL) { HDfprintf(f, "%s: spans=%p, count=%u, bounds[0]={%Hu, %Hu}, head=%p\n", __func__, span_lst, span_lst->count, span_lst->low_bounds[0], span_lst->high_bounds[0], span_lst->head); H5S__hyper_print_spans_helper(f, span_lst->head, 0); } /* end if */ FUNC_LEAVE_NOAPI(SUCCEED) } static herr_t H5S__space_print_spans(FILE *f, const H5S_t *space) { FUNC_ENTER_STATIC_NOERR H5S__hyper_print_spans(f, space->select.sel_info.hslab->span_lst); FUNC_LEAVE_NOAPI(SUCCEED) } static herr_t H5S__hyper_print_diminfo_helper(FILE *f, const char *field, unsigned ndims, const H5S_hyper_dim_t *dinfo) { unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR if (dinfo != NULL) { HDfprintf(f, "%s: %s: start=[", __func__, field); for (u = 0; u < ndims; u++) HDfprintf(f, "%Hd%s", dinfo[u].start, (u < (ndims - 1) ? ", " : "]\n")); HDfprintf(f, "%s: %s: stride=[", __func__, field); for (u = 0; u < ndims; u++) HDfprintf(f, "%Hu%s", dinfo[u].stride, (u < (ndims - 1) ? ", " : "]\n")); HDfprintf(f, "%s: %s: count=[", __func__, field); for (u = 0; u < ndims; u++) HDfprintf(f, "%Hu%s", dinfo[u].count, (u < (ndims - 1) ? ", " : "]\n")); HDfprintf(f, "%s: %s: block=[", __func__, field); for (u = 0; u < ndims; u++) HDfprintf(f, "%Hu%s", dinfo[u].block, (u < (ndims - 1) ? ", " : "]\n")); } /* end if */ else HDfprintf(f, "%s: %s==NULL\n", __func__, field); FUNC_LEAVE_NOAPI(SUCCEED) } static herr_t H5S__hyper_print_diminfo(FILE *f, const H5S_t *space) { FUNC_ENTER_STATIC_NOERR H5S__hyper_print_diminfo_helper(f, "diminfo.opt", space->extent.rank, space->select.sel_info.hslab->diminfo.opt); H5S__hyper_print_diminfo_helper(f, "diminfo.app", space->extent.rank, space->select.sel_info.hslab->diminfo.app); FUNC_LEAVE_NOAPI(SUCCEED) } /*-------------------------------------------------------------------------- NAME H5S__hyper_print_spans_dfs PURPOSE Output the span elements for one span list in depth-first order USAGE herr_t H5S__hyper_print_spans_dfs(f, span_lst, depth) FILE *f; IN: the file to output const H5S_hyper_span_info_t *span_lst; IN: the span list to output unsigned depth; IN: the level of this span list RETURNS non-negative on success, negative on failure GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_print_spans_dfs(FILE *f, const H5S_hyper_span_info_t *span_lst, unsigned depth, unsigned dims) { H5S_hyper_span_t *actual_tail = NULL; H5S_hyper_span_t *cur_elem; unsigned num_elems = 0; unsigned u, elem_idx; FUNC_ENTER_STATIC_NOERR /* get the actual tail from head */ cur_elem = span_lst->head; HDassert(cur_elem); /* at least 1 element */ while (cur_elem) { actual_tail = cur_elem; cur_elem = cur_elem->next; num_elems++; } /* end while */ for (u = 0; u < depth; u++) HDfprintf(f, "\t"); HDfprintf(f, "DIM[%u]: ref_count=%u, #elems=%u, head=%p, tail=%p, actual_tail=%p, matched=%t\n", depth, span_lst->count, num_elems, span_lst->head, span_lst->tail, actual_tail, (span_lst->tail == actual_tail)); for (u = 0; u < depth; u++) HDfprintf(f, "\t"); HDfprintf(f, "low_bounds=["); for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", span_lst->low_bounds[u]); HDfprintf(f, "%llu]\n", span_lst->low_bounds[dims - 1]); for (u = 0; u < depth; u++) HDfprintf(f, "\t"); HDfprintf(f, "high_bounds=["); for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", span_lst->high_bounds[u]); HDfprintf(f, "%llu]\n", span_lst->high_bounds[dims - 1]); cur_elem = span_lst->head; elem_idx = 0; while (cur_elem) { for (u = 0; u < depth; u++) HDfprintf(f, "\t"); HDfprintf(f, "ELEM[%u]: ptr=%p, low=%Hu, high=%Hu, down=%p\n", elem_idx++, cur_elem, cur_elem->low, cur_elem->high, cur_elem->down); if (cur_elem->down) H5S__hyper_print_spans_dfs(f, cur_elem->down, depth + 1, dims); cur_elem = cur_elem->next; } /* end while */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_print_spans_dfs() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_print_space_dfs PURPOSE Output the span elements for one hyperslab selection space in depth-first order USAGE herr_t H5S__hyper_print_space_dfs(f, space) FILE *f; IN: the file to output const H5S_t *space; IN: the selection space to output RETURNS non-negative on success, negative on failure GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_print_space_dfs(FILE *f, const H5S_t *space) { const H5S_hyper_sel_t *hslab = space->select.sel_info.hslab; const unsigned dims = space->extent.rank; unsigned u; FUNC_ENTER_STATIC_NOERR HDassert(hslab); HDfprintf(f, "=======================\n"); HDfprintf(f, "SPACE: span_lst=%p, #dims=%u, offset_changed=%d\n", hslab->span_lst, dims, space->select.offset_changed); HDfprintf(f, " offset=["); for (u = 0; u < dims - 1; u++) HDfprintf(f, "%lld,", space->select.offset[u]); HDfprintf(f, "%lld]\n", space->select.offset[dims - 1]); HDfprintf(f, " low_bounds=["); if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", space->select.sel_info.hslab->diminfo.low_bounds[u]); HDfprintf(f, "%llu]\n", space->select.sel_info.hslab->diminfo.low_bounds[dims - 1]); } /* end if */ else { for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", space->select.sel_info.hslab->span_lst->low_bounds[u]); HDfprintf(f, "%llu]\n", space->select.sel_info.hslab->span_lst->low_bounds[dims - 1]); } /* end else */ HDfprintf(f, " high_bounds=["); if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", space->select.sel_info.hslab->diminfo.high_bounds[u]); HDfprintf(f, "%llu]\n", space->select.sel_info.hslab->diminfo.high_bounds[dims - 1]); } /* end if */ else { for (u = 0; u < dims - 1; u++) HDfprintf(f, "%llu,", space->select.sel_info.hslab->span_lst->high_bounds[u]); HDfprintf(f, "%llu]\n", space->select.sel_info.hslab->span_lst->high_bounds[dims - 1]); } /* end else */ /* Print out diminfo, if it's valid */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) H5S__hyper_print_diminfo(f, space); /* Start print out the highest-order of dimension */ if (hslab->span_lst) H5S__hyper_print_spans_dfs(f, hslab->span_lst, 0, dims); HDfprintf(f, "=======================\n\n"); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_print_space_dfs() */ #endif /* H5S_HYPER_DEBUG */ /*------------------------------------------------------------------------- * Function: H5S__hyper_get_op_gen * * Purpose: Acquire a unique operation generation value * * Return: Operation generation value (can't fail) * * Programmer: Quincey Koziol * Saturday, January 19, 2019 * * Notes: Assumes that a 64-bit value will not wrap around during * the lifespan of the process. * *------------------------------------------------------------------------- */ uint64_t H5S__hyper_get_op_gen(void) { FUNC_ENTER_PACKAGE_NOERR FUNC_LEAVE_NOAPI(H5S_hyper_op_gen_g++); } /* end H5S__hyper_op_gen() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_init * * Purpose: Initializes iteration information for hyperslab selection. * * Return: Non-negative on success, negative on failure. * * Programmer: Quincey Koziol * Saturday, February 24, 2001 * * Notes: If the 'iter->elmt_size' field is set to zero, the regular * hyperslab selection iterator will not be 'flattened'. This * is used by the H5S_select_shape_same() code to avoid changing * the rank and appearance of the selection. * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_iter_init(const H5S_t *space, H5S_sel_iter_t *iter) { hsize_t *slab_size; /* Pointer to the dataspace dimensions to use for calc. slab */ hsize_t acc; /* Accumulator for computing cumulative sizes */ unsigned slab_dim; /* Rank of the fastest changing dimension for calc. slab */ unsigned rank; /* Dataspace's dimension rank */ unsigned u; /* Index variable */ int i; /* Index variable */ herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(space)); HDassert(iter); HDassert(space->select.sel_info.hslab->unlim_dim < 0); /* Initialize the hyperslab iterator's rank */ iter->u.hyp.iter_rank = 0; /* Get the rank of the dataspace */ rank = iter->rank; /* Attempt to rebuild diminfo if it is invalid and has not been confirmed * to be impossible. */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild((H5S_t *)space); /* Casting away const OK -NAF */ /* Check for the special case of just one H5Sselect_hyperslab call made */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { /* Initialize the information needed for regular hyperslab I/O */ const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ const hsize_t * mem_size; /* Temporary pointer to dataspace extent's dimension sizes */ unsigned cont_dim = 0; /* # of contiguous dimensions */ /* Set the temporary pointer to the dimension information */ tdiminfo = space->select.sel_info.hslab->diminfo.opt; /* Set the temporary pointer to the dataspace extent's dimension sizes */ mem_size = iter->dims; /* * For a regular hyperslab to be contiguous up to some dimension, it * must have only one block (i.e. count==1 in all dimensions up to that * dimension) and the block size must be the same as the dataspace's * extent in that dimension and all dimensions up to that dimension. */ /* Don't flatten adjacent elements into contiguous block if the * element size is 0. This is for the H5S_select_shape_same() code. */ if (iter->elmt_size > 0) { /* Check for any "contiguous" blocks that can be flattened */ for (u = (rank - 1); u > 0; u--) { if (tdiminfo[u].count == 1 && tdiminfo[u].block == mem_size[u]) { cont_dim++; iter->u.hyp.flattened[u] = TRUE; } /* end if */ else iter->u.hyp.flattened[u] = FALSE; } /* end for */ iter->u.hyp.flattened[0] = FALSE; } /* end if */ /* Check if the regular selection can be "flattened" */ if (cont_dim > 0) { hbool_t last_dim_flattened = TRUE; /* Flag to indicate that the last dimension was flattened */ unsigned flat_rank = rank - cont_dim; /* Number of dimensions after flattening */ unsigned curr_dim; /* Current dimension */ /* Set the iterator's rank to the contiguous dimensions */ iter->u.hyp.iter_rank = flat_rank; /* "Flatten" dataspace extent and selection information */ curr_dim = flat_rank - 1; for (i = (int)rank - 1, acc = 1; i >= 0; i--) { if (tdiminfo[i].block == mem_size[i] && i > 0) { /* "Flatten" this dimension */ HDassert(tdiminfo[i].start == 0); acc *= mem_size[i]; /* Indicate that the dimension was flattened */ last_dim_flattened = TRUE; } /* end if */ else { if (last_dim_flattened) { /* First dimension after flattened dimensions */ iter->u.hyp.diminfo[curr_dim].start = tdiminfo[i].start * acc; /* Special case for single block regular selections */ if (tdiminfo[i].count == 1) iter->u.hyp.diminfo[curr_dim].stride = 1; else iter->u.hyp.diminfo[curr_dim].stride = tdiminfo[i].stride * acc; iter->u.hyp.diminfo[curr_dim].count = tdiminfo[i].count; iter->u.hyp.diminfo[curr_dim].block = tdiminfo[i].block * acc; iter->u.hyp.size[curr_dim] = mem_size[i] * acc; iter->u.hyp.sel_off[curr_dim] = iter->sel_off[i] * (hssize_t)acc; /* Reset the "last dim flattened" flag to avoid flattened any further dimensions */ last_dim_flattened = FALSE; /* Reset the "accumulator" for possible further dimension flattening */ acc = 1; } /* end if */ else { /* All other dimensions */ iter->u.hyp.diminfo[curr_dim].start = tdiminfo[i].start; iter->u.hyp.diminfo[curr_dim].stride = tdiminfo[i].stride; iter->u.hyp.diminfo[curr_dim].count = tdiminfo[i].count; iter->u.hyp.diminfo[curr_dim].block = tdiminfo[i].block; iter->u.hyp.size[curr_dim] = mem_size[i]; iter->u.hyp.sel_off[curr_dim] = iter->sel_off[i]; } /* end else */ /* Decrement "current" flattened dimension */ curr_dim--; } /* end if */ } /* end for */ /* Initialize "flattened" iterator offset to initial location and dataspace extent and selection * information to correct values */ for (u = 0; u < flat_rank; u++) iter->u.hyp.off[u] = iter->u.hyp.diminfo[u].start; /* Set up information for computing slab sizes */ slab_dim = iter->u.hyp.iter_rank - 1; slab_size = iter->u.hyp.size; } /* end if */ else { /* Make local copy of the regular selection information */ HDcompile_assert(sizeof(iter->u.hyp.diminfo) == sizeof(space->select.sel_info.hslab->diminfo.opt)); H5MM_memcpy(iter->u.hyp.diminfo, tdiminfo, sizeof(iter->u.hyp.diminfo)); /* Initialize position to initial location */ for (u = 0; u < rank; u++) iter->u.hyp.off[u] = tdiminfo[u].start; /* Set up information for computing slab sizes */ slab_dim = iter->rank - 1; slab_size = iter->dims; } /* end else */ /* Flag the diminfo information as valid in the iterator */ iter->u.hyp.diminfo_valid = TRUE; /* Initialize irregular region information also (for release) */ iter->u.hyp.spans = NULL; } /* end if */ else { /* Initialize the information needed for non-regular hyperslab I/O */ H5S_hyper_span_info_t *spans; /* Pointer to hyperslab span info node */ /* If this iterator is created from an API call, by default we clone the * selection now, as the dataspace could be modified or go out of scope. * * However, if the H5S_SEL_ITER_SHARE_WITH_DATASPACE flag is given, * the selection is shared between the selection iterator and the * dataspace. In this case, the application _must_not_ modify or * close the dataspace that the iterator is operating on, or undefined * behavior will occur. */ if ((iter->flags & H5S_SEL_ITER_API_CALL) && !(iter->flags & H5S_SEL_ITER_SHARE_WITH_DATASPACE)) { /* Copy the span tree */ if (NULL == (iter->u.hyp.spans = H5S__hyper_copy_span(space->select.sel_info.hslab->span_lst, space->extent.rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "can't copy span tree") } /* end if */ else { /* Share the source dataspace's span tree by incrementing the reference count on it */ HDassert(space->select.sel_info.hslab->span_lst); iter->u.hyp.spans = space->select.sel_info.hslab->span_lst; iter->u.hyp.spans->count++; } /* end else */ /* Initialize the starting span_info's and spans */ spans = iter->u.hyp.spans; for (u = 0; u < rank; u++) { /* Set the pointers to the initial span in each dimension */ HDassert(spans); HDassert(spans->head); /* Set the pointer to the first span in the list for this node */ iter->u.hyp.span[u] = spans->head; /* Set the initial offset to low bound of span */ iter->u.hyp.off[u] = iter->u.hyp.span[u]->low; /* Get the pointer to the next level down */ spans = spans->head->down; } /* end for */ /* Set up information for computing slab sizes */ slab_dim = iter->rank - 1; slab_size = iter->dims; /* Flag the diminfo information as not valid in the iterator */ iter->u.hyp.diminfo_valid = FALSE; } /* end else */ /* Compute the cumulative size of dataspace dimensions */ for (i = (int)slab_dim, acc = iter->elmt_size; i >= 0; i--) { iter->u.hyp.slab[i] = acc; acc *= slab_size[i]; } /* end for */ /* Initialize more information for irregular hyperslab selections */ if (!iter->u.hyp.diminfo_valid) { /* Set the offset of the first element iterated on, in each dimension */ for (u = 0; u < rank; u++) /* Compute the sequential element offset */ iter->u.hyp.loc_off[u] = ((hsize_t)((hssize_t)iter->u.hyp.off[u] + iter->sel_off[u])) * iter->u.hyp.slab[u]; } /* end if */ /* Initialize type of selection iterator */ iter->type = H5S_sel_iter_hyper; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_iter_init() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_coords * * Purpose: Retrieve the current coordinates of iterator for current * selection * * Return: Non-negative on success, negative on failure * * Programmer: Quincey Koziol * Tuesday, April 22, 2003 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_iter_coords(const H5S_sel_iter_t *iter, hsize_t *coords) { FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(coords); /* Copy the offset of the current point */ /* Check for a single "regular" hyperslab */ if (iter->u.hyp.diminfo_valid) { /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) { int u, v; /* Dimension indices */ /* Set the starting rank of both the "natural" & "flattened" dimensions */ u = (int)iter->rank - 1; v = (int)iter->u.hyp.iter_rank - 1; /* Construct the "natural" dimensions from a set of flattened coordinates */ while (u >= 0) { if (iter->u.hyp.flattened[u]) { int begin = u; /* The rank of the first flattened dimension */ /* Walk up through as many flattened dimensions as possible */ do { u--; } while (u >= 0 && iter->u.hyp.flattened[u]); /* Compensate for possibly overshooting dim 0 */ if (u < 0) u = 0; /* Sanity check */ HDassert(v >= 0); /* Compute the coords for the flattened dimensions */ H5VM_array_calc(iter->u.hyp.off[v], (unsigned)((begin - u) + 1), &(iter->dims[u]), &(coords[u])); /* Continue to faster dimension in both indices */ u--; v--; } /* end if */ else { /* Walk up through as many non-flattened dimensions as possible */ while (u >= 0 && !iter->u.hyp.flattened[u]) { /* Sanity check */ HDassert(v >= 0); /* Copy the coordinate */ coords[u] = iter->u.hyp.off[v]; /* Continue to faster dimension in both indices */ u--; v--; } /* end while */ } /* end else */ } /* end while */ HDassert(v < 0); } /* end if */ else H5MM_memcpy(coords, iter->u.hyp.off, sizeof(hsize_t) * iter->rank); } /* end if */ else H5MM_memcpy(coords, iter->u.hyp.off, sizeof(hsize_t) * iter->rank); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_coords() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_block * * Purpose: Retrieve the current block of iterator for current * selection * * Return: Non-negative on success, negative on failure * * Programmer: Quincey Koziol * Monday, June 2, 2003 * * Notes: This routine assumes that the iterator is always located at * the beginning of a block. * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_iter_block(const H5S_sel_iter_t *iter, hsize_t *start, hsize_t *end) { unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(start); HDassert(end); /* Copy the offset of the current point */ /* Check for a single "regular" hyperslab */ if (iter->u.hyp.diminfo_valid) { /* Copy the start and compute the end of the block */ for (u = 0; u < iter->rank; u++) { start[u] = iter->u.hyp.off[u]; end[u] = (start[u] + iter->u.hyp.diminfo[u].block) - 1; } } /* end if */ else { /* Copy the start & end of the block */ for (u = 0; u < iter->rank; u++) { start[u] = iter->u.hyp.span[u]->low; end[u] = iter->u.hyp.span[u]->high; } } /* end else */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_block() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_nelmts * * Purpose: Return number of elements left to process in iterator * * Return: Non-negative number of elements on success, zero on failure * * Programmer: Quincey Koziol * Tuesday, June 16, 1998 * *------------------------------------------------------------------------- */ static hsize_t H5S__hyper_iter_nelmts(const H5S_sel_iter_t *iter) { FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); FUNC_LEAVE_NOAPI(iter->elmt_left) } /* end H5S__hyper_iter_nelmts() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_has_next_block PURPOSE Check if there is another block left in the current iterator USAGE htri_t H5S__hyper_iter_has_next_block(iter) const H5S_sel_iter_t *iter; IN: Pointer to selection iterator RETURNS Non-negative (TRUE/FALSE) on success/Negative on failure DESCRIPTION Check if there is another block available in the selection iterator. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE htri_t H5S__hyper_iter_has_next_block(const H5S_sel_iter_t *iter) { unsigned u; /* Local index variable */ htri_t ret_value = FALSE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); /* Check for a single "regular" hyperslab */ if (iter->u.hyp.diminfo_valid) { const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ const hsize_t * toff; /* Temporary offset in selection */ /* Check if the offset of the iterator is at the last location in all dimensions */ tdiminfo = iter->u.hyp.diminfo; toff = iter->u.hyp.off; for (u = 0; u < iter->rank; u++) { /* If there is only one block, continue */ if (tdiminfo[u].count == 1) continue; if (toff[u] != (tdiminfo[u].start + ((tdiminfo[u].count - 1) * tdiminfo[u].stride))) HGOTO_DONE(TRUE); } /* end for */ } /* end if */ else { /* Check for any levels of the tree with more sequences in them */ for (u = 0; u < iter->rank; u++) if (iter->u.hyp.span[u]->next != NULL) HGOTO_DONE(TRUE); } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_iter_has_next_block() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_next * * Purpose: Moves a hyperslab iterator to the beginning of the next sequence * of elements to read. Handles walking off the end in all dimensions. * * Return: Success: non-negative * Failure: negative * * Programmer: Quincey Koziol * Friday, September 8, 2000 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_iter_next(H5S_sel_iter_t *iter, size_t nelem) { unsigned ndims; /* Number of dimensions of dataset */ int fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned u; /* Counters */ FUNC_ENTER_STATIC_NOERR /* Check for the special case of just one H5Sselect_hyperslab call made */ /* (i.e. a regular hyperslab selection */ if (iter->u.hyp.diminfo_valid) { const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ hsize_t iter_offset[H5S_MAX_RANK]; hsize_t iter_count[H5S_MAX_RANK]; int temp_dim; /* Temporary rank holder */ /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) /* Set the aliases for the dimension rank */ ndims = iter->u.hyp.iter_rank; else /* Set the aliases for the dimension rank */ ndims = iter->rank; /* Set the fastest dimension rank */ fast_dim = (int)ndims - 1; /* Set the local copy of the diminfo pointer */ tdiminfo = iter->u.hyp.diminfo; /* Calculate the offset and block count for each dimension */ for (u = 0; u < ndims; u++) { if (tdiminfo[u].count == 1) { iter_offset[u] = iter->u.hyp.off[u] - tdiminfo[u].start; iter_count[u] = 0; } /* end if */ else { iter_offset[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) % tdiminfo[u].stride; iter_count[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) / tdiminfo[u].stride; } /* end else */ } /* end for */ /* Loop through, advancing the offset & counts, until all the nelements are accounted for */ while (nelem > 0) { /* Start with the fastest changing dimension */ temp_dim = fast_dim; while (temp_dim >= 0) { if (temp_dim == fast_dim) { size_t actual_elem; /* Actual # of elements advanced on each iteration through loop */ hsize_t block_elem; /* Number of elements left in a block */ /* Compute the number of elements left in block */ block_elem = tdiminfo[temp_dim].block - iter_offset[temp_dim]; /* Compute the number of actual elements to advance */ actual_elem = (size_t)MIN(nelem, block_elem); /* Move the iterator over as many elements as possible */ iter_offset[temp_dim] += actual_elem; /* Decrement the number of elements advanced */ nelem -= actual_elem; } /* end if */ else /* Move to the next row in the current dimension */ iter_offset[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (iter_offset[temp_dim] < tdiminfo[temp_dim].block) break; else { /* Move to the next block in the current dimension */ iter_offset[temp_dim] = 0; iter_count[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (iter_count[temp_dim] < tdiminfo[temp_dim].count) break; else iter_count[temp_dim] = 0; /* reset back to the beginning of the line */ } /* end else */ /* Decrement dimension count */ temp_dim--; } /* end while */ } /* end while */ /* Translate current iter_offset and iter_count into iterator position */ for (u = 0; u < ndims; u++) iter->u.hyp.off[u] = tdiminfo[u].start + (tdiminfo[u].stride * iter_count[u]) + iter_offset[u]; } /* end if */ /* Must be an irregular hyperslab selection */ else { H5S_hyper_span_t * curr_span = NULL; /* Current hyperslab span node */ H5S_hyper_span_t **ispan; /* Iterator's hyperslab span nodes */ hsize_t * abs_arr; /* Absolute hyperslab span position */ int curr_dim; /* Temporary rank holder */ /* Set the rank of the fastest changing dimension */ ndims = iter->rank; fast_dim = (int)ndims - 1; /* Get the pointers to the current span info and span nodes */ abs_arr = iter->u.hyp.off; ispan = iter->u.hyp.span; /* Loop through, advancing the span information, until all the nelements are accounted for */ while (nelem > 0) { /* Start at the fastest dim */ curr_dim = fast_dim; /* Work back up through the dimensions */ while (curr_dim >= 0) { /* Reset the current span */ curr_span = ispan[curr_dim]; /* Increment absolute position */ if (curr_dim == fast_dim) { size_t actual_elem; /* Actual # of elements advanced on each iteration through loop */ hsize_t span_elem; /* Number of elements left in a span */ /* Compute the number of elements left in block */ span_elem = (curr_span->high - abs_arr[curr_dim]) + 1; /* Compute the number of actual elements to advance */ actual_elem = (size_t)MIN(nelem, span_elem); /* Move the iterator over as many elements as possible */ abs_arr[curr_dim] += actual_elem; /* Decrement the number of elements advanced */ nelem -= actual_elem; } /* end if */ else /* Move to the next row in the current dimension */ abs_arr[curr_dim]++; /* Check if we are still within the span */ if (abs_arr[curr_dim] <= curr_span->high) break; /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (curr_span != NULL) { /* Reset the span in the current dimension */ ispan[curr_dim] = curr_span; /* Reset absolute position */ abs_arr[curr_dim] = curr_span->low; break; } /* end if */ else /* If we finished the span list in this dimension, decrement the dimension worked on * and loop again */ curr_dim--; } /* end else */ } /* end while */ /* Check if we are finished with the spans in the tree */ if (curr_dim >= 0) { /* Walk back down the iterator positions, resetting them */ while (curr_dim < fast_dim) { HDassert(curr_span); HDassert(curr_span->down); HDassert(curr_span->down->head); /* Increment current dimension */ curr_dim++; /* Set the new span_info & span for this dimension */ ispan[curr_dim] = curr_span->down->head; /* Advance span down the tree */ curr_span = curr_span->down->head; /* Reset the absolute offset for the dim */ abs_arr[curr_dim] = curr_span->low; } /* end while */ /* Verify that the curr_span points to the fastest dim */ HDassert(curr_span == ispan[fast_dim]); } /* end if */ } /* end while */ } /* end else */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_next() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_iter_next_block * * Purpose: Moves a hyperslab iterator to the beginning of the next sequence * of elements to read. Handles walking off the end in all dimensions. * * Return: Success: non-negative * Failure: negative * * Programmer: Quincey Koziol * Tuesday, June 3, 2003 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_iter_next_block(H5S_sel_iter_t *iter) { unsigned ndims; /* Number of dimensions of dataset */ int fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned u; /* Counters */ FUNC_ENTER_STATIC_NOERR /* Check for the special case of just one H5Sselect_hyperslab call made */ /* (i.e. a regular hyperslab selection) */ if (iter->u.hyp.diminfo_valid) { const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ hsize_t iter_offset[H5S_MAX_RANK]; hsize_t iter_count[H5S_MAX_RANK]; int temp_dim; /* Temporary rank holder */ /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) /* Set the aliases for the dimension rank */ ndims = iter->u.hyp.iter_rank; else /* Set the aliases for the dimension rank */ ndims = iter->rank; /* Set the fastest dimension rank */ fast_dim = (int)ndims - 1; /* Set the local copy of the diminfo pointer */ tdiminfo = iter->u.hyp.diminfo; /* Calculate the offset and block count for each dimension */ for (u = 0; u < ndims; u++) { if (tdiminfo[u].count == 1) { iter_offset[u] = iter->u.hyp.off[u] - tdiminfo[u].start; iter_count[u] = 0; } /* end if */ else { iter_offset[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) % tdiminfo[u].stride; iter_count[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) / tdiminfo[u].stride; } /* end else */ } /* end for */ /* Advance one block */ temp_dim = fast_dim; /* Start with the fastest changing dimension */ while (temp_dim >= 0) { if (temp_dim == fast_dim) /* Move iterator over current block */ iter_offset[temp_dim] += tdiminfo[temp_dim].block; else /* Move to the next row in the current dimension */ iter_offset[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of loop */ if (iter_offset[temp_dim] < tdiminfo[temp_dim].block) break; else { /* Move to the next block in the current dimension */ iter_offset[temp_dim] = 0; iter_count[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (iter_count[temp_dim] < tdiminfo[temp_dim].count) break; else iter_count[temp_dim] = 0; /* reset back to the beginning of the line */ } /* end else */ /* Decrement dimension count */ temp_dim--; } /* end while */ /* Translate current iter_offset and iter_count into iterator position */ for (u = 0; u < ndims; u++) iter->u.hyp.off[u] = tdiminfo[u].start + (tdiminfo[u].stride * iter_count[u]) + iter_offset[u]; } /* end if */ /* Must be an irregular hyperslab selection */ else { H5S_hyper_span_t * curr_span = NULL; /* Current hyperslab span node */ H5S_hyper_span_t **ispan; /* Iterator's hyperslab span nodes */ hsize_t * abs_arr; /* Absolute hyperslab span position */ int curr_dim; /* Temporary rank holder */ /* Set the rank of the fastest changing dimension */ ndims = iter->rank; fast_dim = (int)ndims - 1; /* Get the pointers to the current span info and span nodes */ abs_arr = iter->u.hyp.off; ispan = iter->u.hyp.span; /* Loop through, advancing the span information, until all the nelements are accounted for */ curr_dim = fast_dim; /* Start at the fastest dim */ /* Work back up through the dimensions */ while (curr_dim >= 0) { /* Reset the current span */ curr_span = ispan[curr_dim]; /* Increment absolute position */ if (curr_dim == fast_dim) /* Move the iterator over rest of element in span */ abs_arr[curr_dim] = curr_span->high + 1; else /* Move to the next row in the current dimension */ abs_arr[curr_dim]++; /* Check if we are still within the span */ if (abs_arr[curr_dim] <= curr_span->high) break; /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (curr_span != NULL) { /* Reset the span in the current dimension */ ispan[curr_dim] = curr_span; /* Reset absolute position */ abs_arr[curr_dim] = curr_span->low; break; } /* end if */ else /* If we finished the span list in this dimension, decrement the dimension worked on and * loop again */ curr_dim--; } /* end else */ } /* end while */ /* Check if we are finished with the spans in the tree */ if (curr_dim >= 0) { /* Walk back down the iterator positions, resetting them */ while (curr_dim < fast_dim) { HDassert(curr_span); HDassert(curr_span->down); HDassert(curr_span->down->head); /* Increment current dimension */ curr_dim++; /* Set the new span_info & span for this dimension */ ispan[curr_dim] = curr_span->down->head; /* Advance span down the tree */ curr_span = curr_span->down->head; /* Reset the absolute offset for the dim */ abs_arr[curr_dim] = curr_span->low; } /* end while */ /* Verify that the curr_span points to the fastest dim */ HDassert(curr_span == ispan[fast_dim]); } /* end if */ } /* end else */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_next_block() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_get_seq_list_gen PURPOSE Create a list of offsets & lengths for a selection USAGE herr_t H5S__hyper_iter_get_seq_list_gen(iter,maxseq,maxelem,nseq,nelem,off,len) H5S_sel_iter_t *iter; IN/OUT: Selection iterator describing last position of interest in selection. size_t maxseq; IN: Maximum number of sequences to generate size_t maxelem; IN: Maximum number of elements to include in the generated sequences size_t *nseq; OUT: Actual number of sequences generated size_t *nelem; OUT: Actual number of elements in sequences generated hsize_t *off; OUT: Array of offsets size_t *len; OUT: Array of lengths RETURNS Non-negative on success/Negative on failure DESCRIPTION Use the selection in the dataspace to generate a list of byte offsets and lengths for the region(s) selected. Start/Restart from the position in the ITER parameter. The number of sequences generated is limited by the MAXSEQ parameter and the number of sequences actually generated is stored in the NSEQ parameter. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_iter_get_seq_list_gen(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len) { H5S_hyper_span_t * curr_span; /* Current hyperslab span node */ H5S_hyper_span_t **ispan; /* Iterator's hyperslab span nodes */ hsize_t * slab; /* Cumulative size of each dimension in bytes */ hsize_t loc_off; /* Byte offset in the dataspace */ hsize_t last_span_end = 0; /* The offset of the end of the last span */ hsize_t * abs_arr; /* Absolute hyperslab span position, in elements */ hsize_t * loc_arr; /* Byte offset of hyperslab span position within buffer */ const hssize_t * sel_off; /* Offset within the dataspace extent */ size_t span_elmts = 0; /* Number of elements to actually use for this span */ size_t span_size = 0; /* Number of bytes in current span to actually process */ size_t io_left; /* Initial number of elements to process */ size_t io_elmts_left; /* Number of elements left to process */ size_t io_used; /* Number of elements processed */ size_t curr_seq = 0; /* Number of sequence/offsets stored in the arrays */ size_t elem_size; /* Size of each element iterating over */ unsigned ndims; /* Number of dimensions of dataset */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ int curr_dim; /* Current dimension being operated on */ unsigned u; /* Index variable */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(maxseq > 0); HDassert(maxelem > 0); HDassert(nseq); HDassert(nelem); HDassert(off); HDassert(len); /* Set the rank of the fastest changing dimension */ ndims = iter->rank; fast_dim = (ndims - 1); /* Get the pointers to the current span info and span nodes */ curr_span = iter->u.hyp.span[fast_dim]; abs_arr = iter->u.hyp.off; loc_arr = iter->u.hyp.loc_off; slab = iter->u.hyp.slab; sel_off = iter->sel_off; ispan = iter->u.hyp.span; elem_size = iter->elmt_size; /* Set the amount of elements to perform I/O on, etc. */ H5_CHECK_OVERFLOW(iter->elmt_left, hsize_t, size_t); io_elmts_left = io_left = MIN(maxelem, (size_t)iter->elmt_left); /* Set the offset of the first element iterated on */ for (u = 0, loc_off = 0; u < ndims; u++) loc_off += loc_arr[u]; /* Take care of any partial spans leftover from previous I/Os */ if (abs_arr[fast_dim] != curr_span->low) { /* Finish the span in the fastest changing dimension */ /* Compute the number of elements to attempt in this span */ H5_CHECKED_ASSIGN(span_elmts, size_t, ((curr_span->high - abs_arr[fast_dim]) + 1), hsize_t); /* Check number of elements against upper bounds allowed */ if (span_elmts > io_elmts_left) span_elmts = io_elmts_left; /* Set the span_size, in bytes */ span_size = span_elmts * elem_size; /* Add the partial span to the list of sequences */ off[curr_seq] = loc_off; len[curr_seq] = span_size; /* Increment sequence count */ curr_seq++; /* Set the location of the last span's end */ last_span_end = loc_off + span_size; /* Decrement I/O left to perform */ io_elmts_left -= span_elmts; /* Check if we are done */ if (io_elmts_left > 0) { /* Move to next span in fastest changing dimension */ curr_span = curr_span->next; if (NULL != curr_span) { /* Move location offset of destination */ loc_off += (curr_span->low - abs_arr[fast_dim]) * elem_size; /* Move iterator for fastest changing dimension */ abs_arr[fast_dim] = curr_span->low; loc_arr[fast_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[fast_dim])) * slab[fast_dim]; ispan[fast_dim] = curr_span; } /* end if */ } /* end if */ else { /* Advance the hyperslab iterator */ abs_arr[fast_dim] += span_elmts; /* Check if we are still within the span */ if (abs_arr[fast_dim] <= curr_span->high) { /* Sanity check */ HDassert(ispan[fast_dim] == curr_span); /* Update byte offset */ loc_arr[fast_dim] += span_size; } /* end if */ /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (NULL != curr_span) { /* Reset absolute position */ abs_arr[fast_dim] = curr_span->low; /* Update location offset */ loc_arr[fast_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[fast_dim])) * slab[fast_dim]; /* Reset the span in the current dimension */ ispan[fast_dim] = curr_span; } /* end if */ } /* end else */ } /* end else */ /* Adjust iterator pointers */ if (NULL == curr_span) { /* Same as code in main loop */ /* Start at the next fastest dim */ curr_dim = (int)(fast_dim - 1); /* Work back up through the dimensions */ while (curr_dim >= 0) { /* Reset the current span */ curr_span = ispan[curr_dim]; /* Increment absolute position */ abs_arr[curr_dim]++; /* Check if we are still within the span */ if (abs_arr[curr_dim] <= curr_span->high) { /* Update location offset */ loc_arr[curr_dim] += slab[curr_dim]; break; } /* end if */ /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (NULL != curr_span) { /* Reset the span in the current dimension */ ispan[curr_dim] = curr_span; /* Reset absolute position */ abs_arr[curr_dim] = curr_span->low; /* Update byte location */ loc_arr[curr_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[curr_dim])) * slab[curr_dim]; break; } /* end if */ else /* If we finished the span list in this dimension, decrement the dimension worked on * and loop again */ curr_dim--; } /* end else */ } /* end while */ /* Check if we have more spans in the tree */ if (curr_dim >= 0) { /* Walk back down the iterator positions, resetting them */ while ((unsigned)curr_dim < fast_dim) { HDassert(curr_span); HDassert(curr_span->down); HDassert(curr_span->down->head); /* Increment current dimension */ curr_dim++; /* Set the new span_info & span for this dimension */ ispan[curr_dim] = curr_span->down->head; /* Advance span down the tree */ curr_span = curr_span->down->head; /* Reset the absolute offset for the dim */ abs_arr[curr_dim] = curr_span->low; /* Update the location offset */ loc_arr[curr_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[curr_dim])) * slab[curr_dim]; } /* end while */ /* Verify that the curr_span points to the fastest dim */ HDassert(curr_span == ispan[fast_dim]); /* Reset the buffer offset */ for (u = 0, loc_off = 0; u < ndims; u++) loc_off += loc_arr[u]; } /* end else */ else /* We had better be done with I/O or bad things are going to happen... */ HDassert(io_elmts_left == 0); } /* end if */ } /* end if */ /* Perform the I/O on the elements, based on the position of the iterator */ while (io_elmts_left > 0 && curr_seq < maxseq) { H5S_hyper_span_t *prev_span; /* Previous hyperslab span node */ /* Sanity check */ HDassert(curr_span); /* Set to current span, so the first adjustment to loc_off is 0 */ prev_span = curr_span; /* Loop over all the spans in the fastest changing dimension */ while (curr_span != NULL) { hsize_t nelmts; /* # of elements covered by current span */ /* Move location offset of current span */ loc_off += (curr_span->low - prev_span->low) * elem_size; /* Compute the number of elements to attempt in this span */ nelmts = (curr_span->high - curr_span->low) + 1; H5_CHECKED_ASSIGN(span_elmts, size_t, nelmts, hsize_t); /* Check number of elements against upper bounds allowed */ if (span_elmts >= io_elmts_left) { /* Trim the number of elements to output */ span_elmts = io_elmts_left; span_size = span_elmts * elem_size; io_elmts_left = 0; /* COMMON */ /* Store the I/O information for the span */ /* Check if this is appending onto previous sequence */ if (curr_seq > 0 && last_span_end == loc_off) len[curr_seq - 1] += span_size; else { off[curr_seq] = loc_off; len[curr_seq] = span_size; /* Increment the number of sequences in arrays */ curr_seq++; } /* end else */ /* end COMMON */ /* Break out now, we are finished with I/O */ break; } /* end if */ else { /* Decrement I/O left to perform */ span_size = span_elmts * elem_size; io_elmts_left -= span_elmts; /* COMMON */ /* Store the I/O information for the span */ /* Check if this is appending onto previous sequence */ if (curr_seq > 0 && last_span_end == loc_off) len[curr_seq - 1] += span_size; else { off[curr_seq] = loc_off; len[curr_seq] = span_size; /* Increment the number of sequences in arrays */ curr_seq++; } /* end else */ /* end COMMON */ /* If the sequence & offset arrays are full, do what? */ if (curr_seq >= maxseq) /* Break out now, we are finished with sequences */ break; } /* end else */ /* Set the location of the last span's end */ last_span_end = loc_off + span_size; /* Move to next span in fastest changing dimension */ prev_span = curr_span; curr_span = curr_span->next; } /* end while */ /* Check if we are done */ if (io_elmts_left == 0 || curr_seq >= maxseq) { /* Sanity checks */ HDassert(curr_span); /* Update absolute position */ abs_arr[fast_dim] = curr_span->low + span_elmts; /* Check if we are still within the span */ if (abs_arr[fast_dim] <= curr_span->high) { /* Reset the span for the fast dimension */ ispan[fast_dim] = curr_span; /* Update location offset */ loc_arr[fast_dim] = ((hsize_t)((hssize_t)curr_span->low + (hssize_t)span_elmts + sel_off[fast_dim])) * slab[fast_dim]; break; } /* end if */ /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (curr_span != NULL) { /* Reset absolute position */ abs_arr[fast_dim] = curr_span->low; loc_arr[fast_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[fast_dim])) * slab[fast_dim]; ispan[fast_dim] = curr_span; break; } /* end if */ } /* end else */ } /* end if */ /* Adjust iterator pointers */ /* Start at the next fastest dim */ curr_dim = (int)(fast_dim - 1); /* Work back up through the dimensions */ while (curr_dim >= 0) { /* Reset the current span */ curr_span = ispan[curr_dim]; /* Increment absolute position */ abs_arr[curr_dim]++; /* Check if we are still within the span */ if (abs_arr[curr_dim] <= curr_span->high) { /* Update location offset */ loc_arr[curr_dim] += slab[curr_dim]; break; } /* end if */ /* If we walked off that span, advance to the next span */ else { /* Advance span in this dimension */ curr_span = curr_span->next; /* Check if we have a valid span in this dimension still */ if (curr_span != NULL) { /* Reset the span in the current dimension */ ispan[curr_dim] = curr_span; /* Reset absolute position */ abs_arr[curr_dim] = curr_span->low; /* Update location offset */ loc_arr[curr_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[curr_dim])) * slab[curr_dim]; break; } /* end if */ else /* If we finished the span list in this dimension, decrement the dimension worked on and * loop again */ curr_dim--; } /* end else */ } /* end while */ /* Check if we are finished with the spans in the tree */ if (curr_dim < 0) { /* We had better be done with I/O or bad things are going to happen... */ HDassert(io_elmts_left == 0); break; } /* end if */ else { /* Walk back down the iterator positions, resetting them */ while ((unsigned)curr_dim < fast_dim) { HDassert(curr_span); HDassert(curr_span->down); HDassert(curr_span->down->head); /* Increment current dimension to the next dimension down */ curr_dim++; /* Set the new span for the next dimension down */ ispan[curr_dim] = curr_span->down->head; /* Advance span down the tree */ curr_span = curr_span->down->head; /* Reset the absolute offset for the dim */ abs_arr[curr_dim] = curr_span->low; /* Update location offset */ loc_arr[curr_dim] = ((hsize_t)((hssize_t)curr_span->low + sel_off[curr_dim])) * slab[curr_dim]; } /* end while */ /* Verify that the curr_span points to the fastest dim */ HDassert(curr_span == ispan[fast_dim]); } /* end else */ /* Reset the buffer offset */ for (u = 0, loc_off = 0; u < ndims; u++) loc_off += loc_arr[u]; } /* end while */ /* Decrement number of elements left in iterator */ io_used = io_left - io_elmts_left; iter->elmt_left -= io_used; /* Set the number of sequences generated */ *nseq = curr_seq; /* Set the number of elements used */ *nelem = io_used; FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_get_seq_list_gen() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_get_seq_list_opt PURPOSE Create a list of offsets & lengths for a selection USAGE herr_t H5S__hyper_iter_get_seq_list_opt(iter,maxseq,maxelem,nseq,nelem,off,len) H5S_sel_iter_t *iter; IN/OUT: Selection iterator describing last position of interest in selection. size_t maxseq; IN: Maximum number of sequences to generate size_t maxelem; IN: Maximum number of elements to include in the generated sequences size_t *nseq; OUT: Actual number of sequences generated size_t *nelem; OUT: Actual number of elements in sequences generated hsize_t *off; OUT: Array of offsets size_t *len; OUT: Array of lengths RETURNS Non-negative on success/Negative on failure. DESCRIPTION Use the selection in the dataspace to generate a list of byte offsets and lengths for the region(s) selected. Start/Restart from the position in the ITER parameter. The number of sequences generated is limited by the MAXSEQ parameter and the number of sequences actually generated is stored in the NSEQ parameter. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_iter_get_seq_list_opt(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len) { hsize_t * mem_size; /* Size of the source buffer */ hsize_t * slab; /* Hyperslab size */ const hssize_t * sel_off; /* Selection offset in dataspace */ hsize_t offset[H5S_MAX_RANK]; /* Coordinate offset in dataspace */ hsize_t tmp_count[H5S_MAX_RANK]; /* Temporary block count */ hsize_t tmp_block[H5S_MAX_RANK]; /* Temporary block offset */ hsize_t wrap[H5S_MAX_RANK]; /* Bytes to wrap around at the end of a row */ hsize_t skip[H5S_MAX_RANK]; /* Bytes to skip between blocks */ const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ hsize_t fast_dim_start, /* Local copies of fastest changing dimension info */ fast_dim_stride, fast_dim_block, fast_dim_offset; size_t fast_dim_buf_off; /* Local copy of amount to move fastest dimension buffer offset */ size_t fast_dim_count; /* Number of blocks left in fastest changing dimension */ size_t tot_blk_count; /* Total number of blocks left to output */ size_t act_blk_count; /* Actual number of blocks to output */ size_t total_rows; /* Total number of entire rows to output */ size_t curr_rows; /* Current number of entire rows to output */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned ndims; /* Number of dimensions of dataset */ int temp_dim; /* Temporary rank holder */ hsize_t loc; /* Coordinate offset */ size_t curr_seq = 0; /* Current sequence being operated on */ size_t actual_elem; /* The actual number of elements to count */ size_t actual_bytes; /* The actual number of bytes to copy */ size_t io_left; /* The number of elements left in I/O operation */ size_t start_io_left; /* The initial number of elements left in I/O operation */ size_t elem_size; /* Size of each element iterating over */ unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(maxseq > 0); HDassert(maxelem > 0); HDassert(nseq); HDassert(nelem); HDassert(off); HDassert(len); /* Set the local copy of the diminfo pointer */ tdiminfo = iter->u.hyp.diminfo; /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) { /* Set the aliases for a few important dimension ranks */ ndims = iter->u.hyp.iter_rank; /* Set the local copy of the selection offset */ sel_off = iter->u.hyp.sel_off; /* Set up the pointer to the size of the memory dataspace */ mem_size = iter->u.hyp.size; } /* end if */ else { /* Set the aliases for a few important dimension ranks */ ndims = iter->rank; /* Set the local copy of the selection offset */ sel_off = iter->sel_off; /* Set up the pointer to the size of the memory dataspace */ mem_size = iter->dims; } /* end else */ /* Set up some local variables */ fast_dim = ndims - 1; elem_size = iter->elmt_size; slab = iter->u.hyp.slab; /* Calculate the number of elements to sequence through */ H5_CHECK_OVERFLOW(iter->elmt_left, hsize_t, size_t); io_left = MIN((size_t)iter->elmt_left, maxelem); /* Sanity check that there aren't any "remainder" sequences in process */ HDassert(!((iter->u.hyp.off[fast_dim] - tdiminfo[fast_dim].start) % tdiminfo[fast_dim].stride != 0 || ((iter->u.hyp.off[fast_dim] != tdiminfo[fast_dim].start) && tdiminfo[fast_dim].count == 1))); /* We've cleared the "remainder" of the previous fastest dimension * sequence before calling this routine, so we must be at the beginning of * a sequence. Use the fancy algorithm to compute the offsets and run * through as many as possible, until the buffer fills up. */ /* Keep the number of elements we started with */ start_io_left = io_left; /* Compute the arrays to perform I/O on */ /* Copy the location of the point to get */ /* (Add in the selection offset) */ for (u = 0; u < ndims; u++) offset[u] = (hsize_t)((hssize_t)iter->u.hyp.off[u] + sel_off[u]); /* Compute the current "counts" for this location */ for (u = 0; u < ndims; u++) { if (tdiminfo[u].count == 1) { tmp_count[u] = 0; tmp_block[u] = iter->u.hyp.off[u] - tdiminfo[u].start; } /* end if */ else { tmp_count[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) / tdiminfo[u].stride; tmp_block[u] = (iter->u.hyp.off[u] - tdiminfo[u].start) % tdiminfo[u].stride; } /* end else */ } /* end for */ /* Compute the initial buffer offset */ for (u = 0, loc = 0; u < ndims; u++) loc += offset[u] * slab[u]; /* Set the number of elements to write each time */ H5_CHECKED_ASSIGN(actual_elem, size_t, tdiminfo[fast_dim].block, hsize_t); /* Set the number of actual bytes */ actual_bytes = actual_elem * elem_size; /* Set local copies of information for the fastest changing dimension */ fast_dim_start = tdiminfo[fast_dim].start; fast_dim_stride = tdiminfo[fast_dim].stride; fast_dim_block = tdiminfo[fast_dim].block; H5_CHECKED_ASSIGN(fast_dim_buf_off, size_t, slab[fast_dim] * fast_dim_stride, hsize_t); fast_dim_offset = (hsize_t)((hssize_t)fast_dim_start + sel_off[fast_dim]); /* Compute the number of blocks which would fit into the buffer */ H5_CHECK_OVERFLOW(io_left / fast_dim_block, hsize_t, size_t); tot_blk_count = (size_t)(io_left / fast_dim_block); /* Don't go over the maximum number of sequences allowed */ tot_blk_count = MIN(tot_blk_count, (maxseq - curr_seq)); /* Compute the amount to wrap at the end of each row */ for (u = 0; u < ndims; u++) wrap[u] = (mem_size[u] - (tdiminfo[u].stride * tdiminfo[u].count)) * slab[u]; /* Compute the amount to skip between blocks */ for (u = 0; u < ndims; u++) skip[u] = (tdiminfo[u].stride - tdiminfo[u].block) * slab[u]; /* Check if there is a partial row left (with full blocks) */ if (tmp_count[fast_dim] > 0) { /* Get number of blocks in fastest dimension */ H5_CHECKED_ASSIGN(fast_dim_count, size_t, tdiminfo[fast_dim].count - tmp_count[fast_dim], hsize_t); /* Make certain this entire row will fit into buffer */ fast_dim_count = MIN(fast_dim_count, tot_blk_count); /* Number of blocks to sequence over */ act_blk_count = fast_dim_count; /* Loop over all the blocks in the fastest changing dimension */ while (fast_dim_count > 0) { /* Store the sequence information */ off[curr_seq] = loc; len[curr_seq] = actual_bytes; /* Increment sequence count */ curr_seq++; /* Increment information to reflect block just processed */ loc += fast_dim_buf_off; /* Decrement number of blocks */ fast_dim_count--; } /* end while */ /* Decrement number of elements left */ io_left -= actual_elem * act_blk_count; /* Decrement number of blocks left */ tot_blk_count -= act_blk_count; /* Increment information to reflect block just processed */ tmp_count[fast_dim] += act_blk_count; /* Check if we finished the entire row of blocks */ if (tmp_count[fast_dim] >= tdiminfo[fast_dim].count) { /* Increment offset in destination buffer */ loc += wrap[fast_dim]; /* Increment information to reflect block just processed */ offset[fast_dim] = fast_dim_offset; /* reset the offset in the fastest dimension */ tmp_count[fast_dim] = 0; /* Increment the offset and count for the other dimensions */ temp_dim = (int)fast_dim - 1; while (temp_dim >= 0) { /* Move to the next row in the curent dimension */ offset[temp_dim]++; tmp_block[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (tmp_block[temp_dim] < tdiminfo[temp_dim].block) break; else { /* Move to the next block in the current dimension */ offset[temp_dim] += (tdiminfo[temp_dim].stride - tdiminfo[temp_dim].block); loc += skip[temp_dim]; tmp_block[temp_dim] = 0; tmp_count[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (tmp_count[temp_dim] < tdiminfo[temp_dim].count) break; else { offset[temp_dim] = (hsize_t)((hssize_t)tdiminfo[temp_dim].start + sel_off[temp_dim]); loc += wrap[temp_dim]; tmp_count[temp_dim] = 0; /* reset back to the beginning of the line */ tmp_block[temp_dim] = 0; } /* end else */ } /* end else */ /* Decrement dimension count */ temp_dim--; } /* end while */ } /* end if */ else { /* Update the offset in the fastest dimension */ offset[fast_dim] += (fast_dim_stride * act_blk_count); } /* end else */ } /* end if */ /* Compute the number of entire rows to read in */ H5_CHECK_OVERFLOW(tot_blk_count / tdiminfo[fast_dim].count, hsize_t, size_t); curr_rows = total_rows = (size_t)(tot_blk_count / tdiminfo[fast_dim].count); /* Reset copy of number of blocks in fastest dimension */ H5_CHECKED_ASSIGN(fast_dim_count, size_t, tdiminfo[fast_dim].count, hsize_t); /* Read in data until an entire sequence can't be written out any longer */ while (curr_rows > 0) { #define DUFF_GUTS \ /* Store the sequence information */ \ off[curr_seq] = loc; \ len[curr_seq] = actual_bytes; \ \ /* Increment sequence count */ \ curr_seq++; \ \ /* Increment information to reflect block just processed */ \ loc += fast_dim_buf_off; #ifdef NO_DUFFS_DEVICE /* Loop over all the blocks in the fastest changing dimension */ while (fast_dim_count > 0) { DUFF_GUTS /* Decrement number of blocks */ fast_dim_count--; } /* end while */ #else /* NO_DUFFS_DEVICE */ { size_t duffs_index; /* Counting index for Duff's device */ duffs_index = (fast_dim_count + 7) / 8; switch (fast_dim_count % 8) { default: HDassert(0 && "This Should never be executed!"); break; case 0: do { DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 7: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 6: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 5: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 4: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 3: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 2: DUFF_GUTS /* FALLTHROUGH */ H5_ATTR_FALLTHROUGH case 1: DUFF_GUTS } while (--duffs_index > 0); } /* end switch */ } #endif /* NO_DUFFS_DEVICE */ #undef DUFF_GUTS /* Increment offset in destination buffer */ loc += wrap[fast_dim]; /* Increment the offset and count for the other dimensions */ temp_dim = (int)fast_dim - 1; while (temp_dim >= 0) { /* Move to the next row in the curent dimension */ offset[temp_dim]++; tmp_block[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of loop */ if (tmp_block[temp_dim] < tdiminfo[temp_dim].block) break; else { /* Move to the next block in the current dimension */ offset[temp_dim] += (tdiminfo[temp_dim].stride - tdiminfo[temp_dim].block); loc += skip[temp_dim]; tmp_block[temp_dim] = 0; tmp_count[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break out of * loop */ if (tmp_count[temp_dim] < tdiminfo[temp_dim].count) break; else { offset[temp_dim] = (hsize_t)((hssize_t)tdiminfo[temp_dim].start + sel_off[temp_dim]); loc += wrap[temp_dim]; tmp_count[temp_dim] = 0; /* reset back to the beginning of the line */ tmp_block[temp_dim] = 0; } /* end else */ } /* end else */ /* Decrement dimension count */ temp_dim--; } /* end while */ /* Decrement the number of rows left */ curr_rows--; } /* end while */ /* Adjust the number of blocks & elements left to transfer */ /* Decrement number of elements left */ H5_CHECK_OVERFLOW(actual_elem * (total_rows * tdiminfo[fast_dim].count), hsize_t, size_t); io_left -= (size_t)(actual_elem * (total_rows * tdiminfo[fast_dim].count)); /* Decrement number of blocks left */ H5_CHECK_OVERFLOW((total_rows * tdiminfo[fast_dim].count), hsize_t, size_t); tot_blk_count -= (size_t)(total_rows * tdiminfo[fast_dim].count); /* Read in partial row of blocks */ if (io_left > 0 && curr_seq < maxseq) { /* Get remaining number of blocks left to output */ fast_dim_count = tot_blk_count; /* Loop over all the blocks in the fastest changing dimension */ while (fast_dim_count > 0) { /* Store the sequence information */ off[curr_seq] = loc; len[curr_seq] = actual_bytes; /* Increment sequence count */ curr_seq++; /* Increment information to reflect block just processed */ loc += fast_dim_buf_off; /* Decrement number of blocks */ fast_dim_count--; } /* end while */ /* Decrement number of elements left */ io_left -= actual_elem * tot_blk_count; /* Increment information to reflect block just processed */ offset[fast_dim] += (fast_dim_stride * tot_blk_count); /* move the offset in the fastest dimension */ /* Handle any leftover, partial blocks in this row */ if (io_left > 0 && curr_seq < maxseq) { actual_elem = io_left; actual_bytes = actual_elem * elem_size; /* Store the sequence information */ off[curr_seq] = loc; len[curr_seq] = actual_bytes; /* Increment sequence count */ curr_seq++; /* Decrement the number of elements left */ io_left -= actual_elem; /* Increment buffer correctly */ offset[fast_dim] += actual_elem; } /* end if */ /* don't bother checking slower dimensions */ HDassert(io_left == 0 || curr_seq == maxseq); } /* end if */ /* Update the iterator */ /* Update the iterator with the location we stopped */ /* (Subtract out the selection offset) */ for (u = 0; u < ndims; u++) iter->u.hyp.off[u] = (hsize_t)((hssize_t)offset[u] - sel_off[u]); /* Decrement the number of elements left in selection */ iter->elmt_left -= (start_io_left - io_left); /* Increment the number of sequences generated */ *nseq += curr_seq; /* Increment the number of elements used */ *nelem += start_io_left - io_left; FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_get_seq_list_opt() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_get_seq_list_single PURPOSE Create a list of offsets & lengths for a selection USAGE herr_t H5S__hyper_iter_get_seq_list_single(flags, iter, maxseq, maxelem, nseq, nelem, off, len) unsigned flags; IN: Flags for extra information about operation H5S_sel_iter_t *iter; IN/OUT: Selection iterator describing last position of interest in selection. size_t maxseq; IN: Maximum number of sequences to generate size_t maxelem; IN: Maximum number of elements to include in the generated sequences size_t *nseq; OUT: Actual number of sequences generated size_t *nelem; OUT: Actual number of elements in sequences generated hsize_t *off; OUT: Array of offsets size_t *len; OUT: Array of lengths RETURNS Non-negative on success/Negative on failure. DESCRIPTION Use the selection in the dataspace to generate a list of byte offsets and lengths for the region(s) selected. Start/Restart from the position in the ITER parameter. The number of sequences generated is limited by the MAXSEQ parameter and the number of sequences actually generated is stored in the NSEQ parameter. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_iter_get_seq_list_single(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len) { const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ const hssize_t * sel_off; /* Selection offset in dataspace */ hsize_t * mem_size; /* Size of the source buffer */ hsize_t base_offset[H5S_MAX_RANK]; /* Base coordinate offset in dataspace */ hsize_t offset[H5S_MAX_RANK]; /* Coordinate offset in dataspace */ hsize_t * slab; /* Hyperslab size */ hsize_t fast_dim_block; /* Local copies of fastest changing dimension info */ hsize_t loc; /* Coordinate offset */ size_t tot_blk_count; /* Total number of blocks left to output */ size_t elem_size; /* Size of each element iterating over */ size_t io_left; /* The number of elements left in I/O operation */ size_t actual_elem; /* The actual number of elements to count */ unsigned ndims; /* Number of dimensions of dataset */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned skip_dim; /* Rank of the dimension to skip along */ unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(maxseq > 0); HDassert(maxelem > 0); HDassert(nseq); HDassert(nelem); HDassert(off); HDassert(len); /* Set a local copy of the diminfo pointer */ tdiminfo = iter->u.hyp.diminfo; /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) { /* Set the aliases for a few important dimension ranks */ ndims = iter->u.hyp.iter_rank; /* Set the local copy of the selection offset */ sel_off = iter->u.hyp.sel_off; /* Set up the pointer to the size of the memory dataspace */ mem_size = iter->u.hyp.size; } /* end if */ else { /* Set the aliases for a few important dimension ranks */ ndims = iter->rank; /* Set the local copy of the selection offset */ sel_off = iter->sel_off; /* Set up the pointer to the size of the memory dataspace */ mem_size = iter->dims; } /* end else */ /* Set up some local variables */ fast_dim = ndims - 1; elem_size = iter->elmt_size; slab = iter->u.hyp.slab; /* Copy the base location of the block */ /* (Add in the selection offset) */ for (u = 0; u < ndims; u++) base_offset[u] = (hsize_t)((hssize_t)tdiminfo[u].start + sel_off[u]); /* Copy the location of the point to get */ /* (Add in the selection offset) */ for (u = 0; u < ndims; u++) offset[u] = (hsize_t)((hssize_t)iter->u.hyp.off[u] + sel_off[u]); /* Compute the initial buffer offset */ for (u = 0, loc = 0; u < ndims; u++) loc += offset[u] * slab[u]; /* Set local copies of information for the fastest changing dimension */ fast_dim_block = tdiminfo[fast_dim].block; /* Calculate the number of elements to sequence through */ H5_CHECK_OVERFLOW(iter->elmt_left, hsize_t, size_t); io_left = MIN((size_t)iter->elmt_left, maxelem); /* Compute the number of blocks which would fit into the buffer */ H5_CHECK_OVERFLOW(io_left / fast_dim_block, hsize_t, size_t); tot_blk_count = (size_t)(io_left / fast_dim_block); /* Don't go over the maximum number of sequences allowed */ tot_blk_count = MIN(tot_blk_count, maxseq); /* Set the number of elements to write each time */ H5_CHECKED_ASSIGN(actual_elem, size_t, fast_dim_block, hsize_t); /* Check for blocks to operate on */ if (tot_blk_count > 0) { size_t actual_bytes; /* The actual number of bytes to copy */ /* Set the number of actual bytes */ actual_bytes = actual_elem * elem_size; /* Check for 1-dim selection */ if (0 == fast_dim) { /* Sanity checks */ HDassert(1 == tot_blk_count); HDassert(io_left == actual_elem); /* Store the sequence information */ *off++ = loc; *len++ = actual_bytes; } /* end if */ else { hsize_t skip_slab; /* Temporary copy of slab[fast_dim - 1] */ size_t blk_count; /* Total number of blocks left to output */ int i; /* Local index variable */ /* Find first dimension w/block >1 */ skip_dim = fast_dim; for (i = (int)(fast_dim - 1); i >= 0; i--) if (tdiminfo[i].block > 1) { skip_dim = (unsigned)i; break; } /* end if */ skip_slab = slab[skip_dim]; /* Check for being able to use fast algorithm for 1-D */ if (0 == skip_dim) { /* Create sequences until an entire row can't be used */ blk_count = tot_blk_count; while (blk_count > 0) { /* Store the sequence information */ *off++ = loc; *len++ = actual_bytes; /* Increment offset in destination buffer */ loc += skip_slab; /* Decrement block count */ blk_count--; } /* end while */ /* Move to the next location */ offset[skip_dim] += tot_blk_count; } /* end if */ else { hsize_t tmp_block[H5S_MAX_RANK]; /* Temporary block offset */ hsize_t skip[H5S_MAX_RANK]; /* Bytes to skip between blocks */ int temp_dim; /* Temporary rank holder */ /* Set the starting block location */ for (u = 0; u < ndims; u++) tmp_block[u] = iter->u.hyp.off[u] - tdiminfo[u].start; /* Compute the amount to skip between sequences */ for (u = 0; u < ndims; u++) skip[u] = (mem_size[u] - tdiminfo[u].block) * slab[u]; /* Create sequences until an entire row can't be used */ blk_count = tot_blk_count; while (blk_count > 0) { /* Store the sequence information */ *off++ = loc; *len++ = actual_bytes; /* Set temporary dimension for advancing offsets */ temp_dim = (int)skip_dim; /* Increment offset in destination buffer */ loc += skip_slab; /* Increment the offset and count for the other dimensions */ while (temp_dim >= 0) { /* Move to the next row in the curent dimension */ offset[temp_dim]++; tmp_block[temp_dim]++; /* If this block is still in the range of blocks to output for the dimension, break * out of loop */ if (tmp_block[temp_dim] < tdiminfo[temp_dim].block) break; else { offset[temp_dim] = base_offset[temp_dim]; loc += skip[temp_dim]; tmp_block[temp_dim] = 0; } /* end else */ /* Decrement dimension count */ temp_dim--; } /* end while */ /* Decrement block count */ blk_count--; } /* end while */ } /* end else */ } /* end else */ /* Update the iterator, if there were any blocks used */ /* Decrement the number of elements left in selection */ iter->elmt_left -= tot_blk_count * actual_elem; /* Check if there are elements left in iterator */ if (iter->elmt_left > 0) { /* Update the iterator with the location we stopped */ /* (Subtract out the selection offset) */ for (u = 0; u < ndims; u++) iter->u.hyp.off[u] = (hsize_t)((hssize_t)offset[u] - sel_off[u]); } /* end if */ /* Increment the number of sequences generated */ *nseq += tot_blk_count; /* Increment the number of elements used */ *nelem += tot_blk_count * actual_elem; } /* end if */ /* Check for partial block, with room for another sequence */ if (io_left > (tot_blk_count * actual_elem) && tot_blk_count < maxseq) { size_t elmt_remainder; /* Elements remaining */ /* Compute elements left */ elmt_remainder = io_left - (tot_blk_count * actual_elem); HDassert(elmt_remainder < fast_dim_block); HDassert(elmt_remainder > 0); /* Store the sequence information */ *off++ = loc; *len++ = elmt_remainder * elem_size; /* Update the iterator with the location we stopped */ iter->u.hyp.off[fast_dim] += (hsize_t)elmt_remainder; /* Decrement the number of elements left in selection */ iter->elmt_left -= elmt_remainder; /* Increment the number of sequences generated */ (*nseq)++; /* Increment the number of elements used */ *nelem += elmt_remainder; } /* end if */ /* Sanity check */ HDassert(*nseq > 0); HDassert(*nelem > 0); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_get_seq_list_single() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_get_seq_list PURPOSE Create a list of offsets & lengths for a selection USAGE herr_t H5S__hyper_iter_get_seq_list(iter,maxseq,maxelem,nseq,nelem,off,len) H5S_t *space; IN: Dataspace containing selection to use. H5S_sel_iter_t *iter; IN/OUT: Selection iterator describing last position of interest in selection. size_t maxseq; IN: Maximum number of sequences to generate size_t maxelem; IN: Maximum number of elements to include in the generated sequences size_t *nseq; OUT: Actual number of sequences generated size_t *nelem; OUT: Actual number of elements in sequences generated hsize_t *off; OUT: Array of offsets (in bytes) size_t *len; OUT: Array of lengths (in bytes) RETURNS Non-negative on success/Negative on failure. DESCRIPTION Use the selection in the dataspace to generate a list of byte offsets and lengths for the region(s) selected. Start/Restart from the position in the ITER parameter. The number of sequences generated is limited by the MAXSEQ parameter and the number of sequences actually generated is stored in the NSEQ parameter. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_iter_get_seq_list(H5S_sel_iter_t *iter, size_t maxseq, size_t maxelem, size_t *nseq, size_t *nelem, hsize_t *off, size_t *len) { herr_t ret_value = FAIL; /* return value */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); HDassert(iter->elmt_left > 0); HDassert(maxseq > 0); HDassert(maxelem > 0); HDassert(nseq); HDassert(nelem); HDassert(off); HDassert(len); /* Check for the special case of just one H5Sselect_hyperslab call made */ if (iter->u.hyp.diminfo_valid) { const H5S_hyper_dim_t *tdiminfo; /* Temporary pointer to diminfo information */ const hssize_t * sel_off; /* Selection offset in dataspace */ unsigned ndims; /* Number of dimensions of dataset */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ hbool_t single_block; /* Whether the selection is a single block */ unsigned u; /* Local index variable */ /* Set a local copy of the diminfo pointer */ tdiminfo = iter->u.hyp.diminfo; /* Check if this is a "flattened" regular hyperslab selection */ if (iter->u.hyp.iter_rank != 0 && iter->u.hyp.iter_rank < iter->rank) { /* Set the aliases for a few important dimension ranks */ ndims = iter->u.hyp.iter_rank; /* Set the local copy of the selection offset */ sel_off = iter->u.hyp.sel_off; } /* end if */ else { /* Set the aliases for a few important dimension ranks */ ndims = iter->rank; /* Set the local copy of the selection offset */ sel_off = iter->sel_off; } /* end else */ fast_dim = ndims - 1; /* Check if we stopped in the middle of a sequence of elements */ if ((iter->u.hyp.off[fast_dim] - tdiminfo[fast_dim].start) % tdiminfo[fast_dim].stride != 0 || ((iter->u.hyp.off[fast_dim] != tdiminfo[fast_dim].start) && tdiminfo[fast_dim].count == 1)) { hsize_t *slab; /* Hyperslab size */ hsize_t loc; /* Coordinate offset */ size_t leftover; /* The number of elements left over from the last sequence */ size_t actual_elem; /* The actual number of elements to count */ size_t elem_size; /* Size of each element iterating over */ /* Calculate the number of elements left in the sequence */ if (tdiminfo[fast_dim].count == 1) { H5_CHECKED_ASSIGN(leftover, size_t, tdiminfo[fast_dim].block - (iter->u.hyp.off[fast_dim] - tdiminfo[fast_dim].start), hsize_t); } /* end if */ else { H5_CHECKED_ASSIGN( leftover, size_t, tdiminfo[fast_dim].block - ((iter->u.hyp.off[fast_dim] - tdiminfo[fast_dim].start) % tdiminfo[fast_dim].stride), hsize_t); } /* end else */ /* Make certain that we don't write too many */ actual_elem = MIN3(leftover, (size_t)iter->elmt_left, maxelem); /* Set up some local variables */ elem_size = iter->elmt_size; slab = iter->u.hyp.slab; /* Compute the initial buffer offset */ for (u = 0, loc = 0; u < ndims; u++) loc += ((hsize_t)((hssize_t)iter->u.hyp.off[u] + sel_off[u])) * slab[u]; /* Add a new sequence */ off[0] = loc; H5_CHECKED_ASSIGN(len[0], size_t, actual_elem * elem_size, hsize_t); /* Increment sequence array locations */ off++; len++; /* Advance the hyperslab iterator */ H5S__hyper_iter_next(iter, actual_elem); /* Decrement the number of elements left in selection */ iter->elmt_left -= actual_elem; /* Decrement element/sequence limits */ maxelem -= actual_elem; maxseq--; /* Set the number of sequences generated and elements used */ *nseq = 1; *nelem = actual_elem; /* Check for using up all the sequences/elements */ if (0 == iter->elmt_left || 0 == maxelem || 0 == maxseq) return (SUCCEED); } /* end if */ else { /* Reset the number of sequences generated and elements used */ *nseq = 0; *nelem = 0; } /* end else */ /* Check for a single block selected */ single_block = TRUE; for (u = 0; u < ndims; u++) if (1 != tdiminfo[u].count) { single_block = FALSE; break; } /* end if */ /* Check for single block selection */ if (single_block) /* Use single-block optimized call to generate sequence list */ ret_value = H5S__hyper_iter_get_seq_list_single(iter, maxseq, maxelem, nseq, nelem, off, len); else /* Use optimized call to generate sequence list */ ret_value = H5S__hyper_iter_get_seq_list_opt(iter, maxseq, maxelem, nseq, nelem, off, len); } /* end if */ else /* Call the general sequence generator routine */ ret_value = H5S__hyper_iter_get_seq_list_gen(iter, maxseq, maxelem, nseq, nelem, off, len); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_iter_get_seq_list() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_iter_release PURPOSE Release hyperslab selection iterator information for a dataspace USAGE herr_t H5S__hyper_iter_release(iter) H5S_sel_iter_t *iter; IN: Pointer to selection iterator RETURNS Non-negative on success/Negative on failure DESCRIPTION Releases all information for a dataspace hyperslab selection iterator GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_iter_release(H5S_sel_iter_t *iter) { FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(iter); /* Free the copy of the hyperslab selection span tree */ if (iter->u.hyp.spans != NULL) H5S__hyper_free_span_info(iter->u.hyp.spans); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_iter_release() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_new_span PURPOSE Make a new hyperslab span node USAGE H5S_hyper_span_t *H5S__hyper_new_span(low, high, down, next) hsize_t low, high; IN: Low and high bounds for new span node H5S_hyper_span_info_t *down; IN: Down span tree for new node H5S_hyper_span_t *next; IN: Next span for new node RETURNS Pointer to new span node on success, NULL on failure DESCRIPTION Allocate and initialize a new hyperslab span node, filling in the low & high bounds, the down span and next span pointers also. Increment the reference count of the 'down span' if applicable. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_t * H5S__hyper_new_span(hsize_t low, hsize_t high, H5S_hyper_span_info_t *down, H5S_hyper_span_t *next) { H5S_hyper_span_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Allocate a new span node */ if (NULL == (ret_value = H5FL_MALLOC(H5S_hyper_span_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Copy the span's basic information */ ret_value->low = low; ret_value->high = high; ret_value->down = down; ret_value->next = next; /* Increment the reference count of the 'down span' if there is one */ if (ret_value->down) ret_value->down->count++; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_new_span() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_new_span_info PURPOSE Make a new hyperslab span info node USAGE H5S_hyper_span_info_t *H5S__hyper_new_span_info(rank) unsigned rank; IN: Rank of span info, in selection RETURNS Pointer to new span node info on success, NULL on failure DESCRIPTION Allocate and initialize a new hyperslab span info node of a given rank, setting up the low & high bound array pointers. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note that this uses the C99 "flexible array member" feature. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_info_t * H5S__hyper_new_span_info(unsigned rank) { H5S_hyper_span_info_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(rank > 0); HDassert(rank <= H5S_MAX_RANK); /* Allocate a new span info node */ if (NULL == (ret_value = (H5S_hyper_span_info_t *)H5FL_ARR_CALLOC(hbounds_t, rank * 2))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span info") /* Set low & high bound pointers into the 'bounds' array */ ret_value->low_bounds = ret_value->bounds; ret_value->high_bounds = &ret_value->bounds[rank]; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_new_span_info() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_copy_span_helper PURPOSE Helper routine to copy a hyperslab span tree USAGE H5S_hyper_span_info_t * H5S__hyper_copy_span_helper(spans, rank, op_info_i, op_gen) H5S_hyper_span_info_t *spans; IN: Span tree to copy unsigned rank; IN: Rank of span tree unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURNS Pointer to the copied span tree on success, NULL on failure DESCRIPTION Copy a hyperslab span tree, using reference counting as appropriate. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_info_t * H5S__hyper_copy_span_helper(H5S_hyper_span_info_t *spans, unsigned rank, unsigned op_info_i, uint64_t op_gen) { H5S_hyper_span_t * span; /* Hyperslab span */ H5S_hyper_span_t * new_span; /* Temporary hyperslab span */ H5S_hyper_span_t * prev_span; /* Previous hyperslab span */ H5S_hyper_span_info_t *new_down; /* New down span tree */ H5S_hyper_span_info_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Sanity checks */ HDassert(spans); /* Check if the span tree was already copied */ if (spans->op_info[op_info_i].op_gen == op_gen) { /* Just return the value of the already copied span tree */ ret_value = spans->op_info[op_info_i].u.copied; /* Increment the reference count of the span tree */ ret_value->count++; } /* end if */ else { /* Allocate a new span_info node */ if (NULL == (ret_value = H5S__hyper_new_span_info(rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span info") /* Set the non-zero span_info information */ H5MM_memcpy(ret_value->low_bounds, spans->low_bounds, rank * sizeof(hsize_t)); H5MM_memcpy(ret_value->high_bounds, spans->high_bounds, rank * sizeof(hsize_t)); ret_value->count = 1; /* Set the operation generation for the span info, to avoid future copies */ spans->op_info[op_info_i].op_gen = op_gen; /* Set the 'copied' pointer in the node being copied to the newly allocated node */ spans->op_info[op_info_i].u.copied = ret_value; /* Copy over the nodes in the span list */ span = spans->head; prev_span = NULL; while (span != NULL) { /* Allocate a new node */ if (NULL == (new_span = H5S__hyper_new_span(span->low, span->high, NULL, NULL))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Append to list of spans */ if (NULL == prev_span) ret_value->head = new_span; else prev_span->next = new_span; /* Recurse to copy the 'down' spans, if there are any */ if (span->down != NULL) { if (NULL == (new_down = H5S__hyper_copy_span_helper(span->down, rank - 1, op_info_i, op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, NULL, "can't copy hyperslab spans") new_span->down = new_down; } /* end if */ /* Update the previous (new) span */ prev_span = new_span; /* Advance to next span */ span = span->next; } /* end while */ /* Retain a pointer to the last span */ ret_value->tail = prev_span; } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_copy_span_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_copy_span PURPOSE Copy a hyperslab span tree USAGE H5S_hyper_span_info_t * H5S__hyper_copy_span(span_info, rank) H5S_hyper_span_info_t *span_info; IN: Span tree to copy unsigned rank; IN: Rank of span tree RETURNS Pointer to the copied span tree on success, NULL on failure DESCRIPTION Copy a hyperslab span tree, using reference counting as appropriate. (Which means that just the nodes in the top span tree are duplicated and the reference counts of their 'down spans' are just incremented) GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_info_t * H5S__hyper_copy_span(H5S_hyper_span_info_t *spans, unsigned rank) { uint64_t op_gen; /* Operation generation value */ H5S_hyper_span_info_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(spans); /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Copy the hyperslab span tree */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ if (NULL == (ret_value = H5S__hyper_copy_span_helper(spans, rank, 0, op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, NULL, "can't copy hyperslab span tree") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_copy_span() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_cmp_spans PURPOSE Check if two hyperslab span trees are the same USAGE hbool_t H5S__hyper_cmp_spans(span1, span2) H5S_hyper_span_info_t *span_info1; IN: First span tree to compare H5S_hyper_span_info_t *span_info2; IN: Second span tree to compare RETURNS TRUE (1) or FALSE (0) on success, can't fail DESCRIPTION Compare two hyperslab span trees to determine if they refer to the same selection. If span1 & span2 are both NULL, that counts as equal. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE hbool_t H5S__hyper_cmp_spans(const H5S_hyper_span_info_t *span_info1, const H5S_hyper_span_info_t *span_info2) { hbool_t ret_value = TRUE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Check for redundant comparison (or both spans being NULL) */ if (span_info1 != span_info2) { /* Check for one span being NULL */ if (span_info1 == NULL || span_info2 == NULL) HGOTO_DONE(FALSE) else { /* Compare low & high bounds for this span list */ /* (Could compare lower dimensions also, but not certain if * that's worth it. - QAK, 2019/01/23) */ if (span_info1->low_bounds[0] != span_info2->low_bounds[0]) HGOTO_DONE(FALSE) else if (span_info1->high_bounds[0] != span_info2->high_bounds[0]) HGOTO_DONE(FALSE) else { const H5S_hyper_span_t *span1; const H5S_hyper_span_t *span2; /* Get the pointers to the actual lists of spans */ span1 = span_info1->head; span2 = span_info2->head; /* Sanity checking */ HDassert(span1); HDassert(span2); /* infinite loop which must be broken out of */ while (1) { /* Check for both spans being NULL */ if (span1 == NULL && span2 == NULL) HGOTO_DONE(TRUE) else { /* Check for one span being NULL */ if (span1 == NULL || span2 == NULL) HGOTO_DONE(FALSE) else { /* Check if the actual low & high span information is the same */ if (span1->low != span2->low || span1->high != span2->high) HGOTO_DONE(FALSE) else { if (span1->down != NULL || span2->down != NULL) { if (!H5S__hyper_cmp_spans(span1->down, span2->down)) HGOTO_DONE(FALSE) else { /* Keep going... */ } /* end else */ } /* end if */ else { /* Keep going... */ } /* end else */ } /* end else */ } /* end else */ } /* end else */ /* Advance to the next nodes in the span list */ span1 = span1->next; span2 = span2->next; } /* end while */ } /* end else */ } /* end else */ } /* end if */ /* Fall through, with default return value of 'TRUE' if spans were already visited */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_cmp_spans() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_free_span_info PURPOSE Free a hyperslab span info node USAGE void H5S__hyper_free_span_info(span_info) H5S_hyper_span_info_t *span_info; IN: Span info node to free RETURNS None DESCRIPTION Free a hyperslab span info node, along with all the span nodes and the 'down spans' from the nodes, if reducing their reference count to zero indicates it is appropriate to do so. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_free_span_info(H5S_hyper_span_info_t *span_info) { FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(span_info); /* Decrement the span tree's reference count */ span_info->count--; /* Free the span tree if the reference count drops to zero */ if (span_info->count == 0) { H5S_hyper_span_t *span; /* Pointer to spans to iterate over */ /* Work through the list of spans pointed to by this 'info' node */ span = span_info->head; while (span != NULL) { H5S_hyper_span_t *next_span; /* Pointer to next span to iterate over */ /* Keep a pointer to the next span */ next_span = span->next; /* Free the current span */ H5S__hyper_free_span(span); /* Advance to next span */ span = next_span; } /* end while */ /* Free this span info */ span_info = (H5S_hyper_span_info_t *)H5FL_ARR_FREE(hbounds_t, span_info); } /* end if */ FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_free_span_info() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_free_span PURPOSE Free a hyperslab span node USAGE void H5S__hyper_free_span(span) H5S_hyper_span_t *span; IN: Span node to free RETURNS None DESCRIPTION Free a hyperslab span node, along with the 'down spans' from the node, if reducing their reference count to zero indicates it is appropriate to do so. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_free_span(H5S_hyper_span_t *span) { FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(span); /* Decrement the reference count of the 'down spans', freeing them if appropriate */ if (span->down != NULL) H5S__hyper_free_span_info(span->down); /* Free this span */ span = H5FL_FREE(H5S_hyper_span_t, span); FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_free_span() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_copy PURPOSE Copy a selection from one dataspace to another USAGE herr_t H5S__hyper_copy(dst, src, share_selection) H5S_t *dst; OUT: Pointer to the destination dataspace H5S_t *src; IN: Pointer to the source dataspace hbool_t; IN: Whether to share the selection between the dataspaces RETURNS Non-negative on success, negative on failure DESCRIPTION Copies all the hyperslab selection information from the source dataspace to the destination dataspace. If the SHARE_SELECTION flag is set, then the selection can be shared between the source and destination dataspaces. (This should only occur in situations where the destination dataspace will immediately change to a new selection) GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_copy(H5S_t *dst, const H5S_t *src, hbool_t share_selection) { H5S_hyper_sel_t * dst_hslab; /* Pointer to destination hyperslab info */ const H5S_hyper_sel_t *src_hslab; /* Pointer to source hyperslab info */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(src); HDassert(dst); /* Allocate space for the hyperslab selection information */ if (NULL == (dst->select.sel_info.hslab = H5FL_MALLOC(H5S_hyper_sel_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab info") /* Set temporary pointers */ dst_hslab = dst->select.sel_info.hslab; src_hslab = src->select.sel_info.hslab; /* Copy the hyperslab information */ dst_hslab->diminfo_valid = src_hslab->diminfo_valid; if (src_hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) H5MM_memcpy(&dst_hslab->diminfo, &src_hslab->diminfo, sizeof(H5S_hyper_diminfo_t)); /* Check if there is hyperslab span information to copy */ /* (Regular hyperslab information is copied with the selection structure) */ if (src->select.sel_info.hslab->span_lst != NULL) { if (share_selection) { /* Share the source's span tree by incrementing the reference count on it */ dst->select.sel_info.hslab->span_lst = src->select.sel_info.hslab->span_lst; dst->select.sel_info.hslab->span_lst->count++; } /* end if */ else /* Copy the hyperslab span information */ dst->select.sel_info.hslab->span_lst = H5S__hyper_copy_span(src->select.sel_info.hslab->span_lst, src->extent.rank); } /* end if */ else dst->select.sel_info.hslab->span_lst = NULL; /* Copy the unlimited dimension info */ dst_hslab->unlim_dim = src_hslab->unlim_dim; dst_hslab->num_elem_non_unlim = src_hslab->num_elem_non_unlim; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_copy() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_is_valid PURPOSE Check whether the selection fits within the extent, with the current offset defined. USAGE htri_t H5S__hyper_is_valid(space); H5S_t *space; IN: Dataspace pointer to query RETURNS TRUE if the selection fits within the extent, FALSE if it does not and Negative on an error. DESCRIPTION Determines if the current selection at the current offset fits within the extent for the dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static htri_t H5S__hyper_is_valid(const H5S_t *space) { const hsize_t *low_bounds, *high_bounds; /* Pointers to the correct pair of low & high bounds */ unsigned u; /* Counter */ htri_t ret_value = TRUE; /* return value */ FUNC_ENTER_STATIC_NOERR HDassert(space); /* Check for unlimited selection */ if (space->select.sel_info.hslab->unlim_dim >= 0) HGOTO_DONE(FALSE) /* Check which set of low & high bounds we should be using */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { low_bounds = space->select.sel_info.hslab->diminfo.low_bounds; high_bounds = space->select.sel_info.hslab->diminfo.high_bounds; } /* end if */ else { low_bounds = space->select.sel_info.hslab->span_lst->low_bounds; high_bounds = space->select.sel_info.hslab->span_lst->high_bounds; } /* end else */ /* Check each dimension */ for (u = 0; u < space->extent.rank; u++) { /* Bounds check the selected point + offset against the extent */ if (((hssize_t)low_bounds[u] + space->select.offset[u]) < 0) HGOTO_DONE(FALSE) if ((high_bounds[u] + (hsize_t)space->select.offset[u]) >= space->extent.size[u]) HGOTO_DONE(FALSE) } /* end for */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_is_valid() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_span_nblocks_helper PURPOSE Helper routine to count the number of blocks in a span tree USAGE hsize_t H5S__hyper_span_nblocks_helper(spans, op_info_i, op_gen) H5S_hyper_span_info_t *spans; IN: Hyperslab span tree to count blocks of unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURNS Number of blocks in span tree on success; negative on failure DESCRIPTION Counts the number of blocks described by the spans in a span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__hyper_span_nblocks_helper(H5S_hyper_span_info_t *spans, unsigned op_info_i, uint64_t op_gen) { hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(spans); /* Check if the span tree was already counted */ if (spans->op_info[op_info_i].op_gen == op_gen) /* Just return the # of blocks in the already counted span tree */ ret_value = spans->op_info[op_info_i].u.nblocks; else { /* Count the number of elements in the span tree */ H5S_hyper_span_t *span; /* Hyperslab span */ span = spans->head; if (span->down) { while (span) { /* If there are down spans, add the total down span blocks */ ret_value += H5S__hyper_span_nblocks_helper(span->down, op_info_i, op_gen); /* Advance to next span */ span = span->next; } /* end while */ } /* end if */ else { while (span) { /* If there are no down spans, just count the block in this span */ ret_value++; /* Advance to next span */ span = span->next; } /* end while */ } /* end else */ /* Set the operation generation for this span tree, to avoid re-computing */ spans->op_info[op_info_i].op_gen = op_gen; /* Hold a copy of the # of blocks */ spans->op_info[op_info_i].u.nblocks = ret_value; } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_span_nblocks_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_span_nblocks PURPOSE Count the number of blocks in a span tree USAGE hsize_t H5S__hyper_span_nblocks(spans) H5S_hyper_span_info_t *spans; IN: Hyperslab span tree to count blocks of RETURNS Number of blocks in span tree on success; negative on failure DESCRIPTION Counts the number of blocks described by the spans in a span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__hyper_span_nblocks(H5S_hyper_span_info_t *spans) { hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Count the number of elements in the span tree */ if (spans != NULL) { uint64_t op_gen; /* Operation generation value */ /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Count the blocks */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ ret_value = H5S__hyper_span_nblocks_helper(spans, 0, op_gen); } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_span_nblocks() */ /*-------------------------------------------------------------------------- NAME H5S__get_select_hyper_nblocks PURPOSE Get the number of hyperslab blocks in current hyperslab selection USAGE hsize_t H5S__get_select_hyper_nblocks(space, app_ref) H5S_t *space; IN: Dataspace ptr of selection to query hbool_t app_ref; IN: Whether this is an appl. ref. call RETURNS The number of hyperslab blocks in selection on success, negative on failure DESCRIPTION Returns the number of hyperslab blocks in current selection for dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__get_select_hyper_nblocks(const H5S_t *space, hbool_t app_ref) { hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR HDassert(space); HDassert(space->select.sel_info.hslab->unlim_dim < 0); /* Check for a "regular" hyperslab selection */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { unsigned u; /* Local index variable */ /* Check each dimension */ for (ret_value = 1, u = 0; u < space->extent.rank; u++) ret_value *= (app_ref ? space->select.sel_info.hslab->diminfo.app[u].count : space->select.sel_info.hslab->diminfo.opt[u].count); } /* end if */ else ret_value = H5S__hyper_span_nblocks(space->select.sel_info.hslab->span_lst); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__get_select_hyper_nblocks() */ /*-------------------------------------------------------------------------- NAME H5Sget_select_hyper_nblocks PURPOSE Get the number of hyperslab blocks in current hyperslab selection USAGE hssize_t H5Sget_select_hyper_nblocks(dsid) hid_t dsid; IN: Dataspace ID of selection to query RETURNS The number of hyperslab blocks in selection on success, negative on failure DESCRIPTION Returns the number of hyperslab blocks in current selection for dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hssize_t H5Sget_select_hyper_nblocks(hid_t spaceid) { H5S_t * space; /* Dataspace to modify selection of */ hssize_t ret_value; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE1("Hs", "i", spaceid); /* Check args */ if (NULL == (space = (H5S_t *)H5I_object_verify(spaceid, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (H5S_GET_SELECT_TYPE(space) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a hyperslab selection") if (space->select.sel_info.hslab->unlim_dim >= 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "cannot get number of blocks for unlimited selection") ret_value = (hssize_t)H5S__get_select_hyper_nblocks(space, TRUE); done: FUNC_LEAVE_API(ret_value) } /* end H5Sget_select_hyper_nblocks() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_get_enc_size_real PURPOSE Determine the size to encode the hyperslab selection info USAGE hssize_t H5S__hyper_get_enc_size_real(max_size, enc_size) hsize_t max_size: IN: The maximum size of the hyperslab selection info unint8_t *enc_size: OUT:The encoding size RETURNS The size to encode hyperslab selection info DESCRIPTION Determine the size by comparing "max_size" with (2^32 - 1) and (2^16 - 1). GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static uint8_t H5S__hyper_get_enc_size_real(hsize_t max_size) { uint8_t ret_value = H5S_SELECT_INFO_ENC_SIZE_2; FUNC_ENTER_STATIC_NOERR if (max_size > H5S_UINT32_MAX) ret_value = H5S_SELECT_INFO_ENC_SIZE_8; else if (max_size > H5S_UINT16_MAX) ret_value = H5S_SELECT_INFO_ENC_SIZE_4; else ret_value = H5S_SELECT_INFO_ENC_SIZE_2; FUNC_LEAVE_NOAPI(ret_value) } /* H5S__hyper_get_enc_size_real() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_get_version_enc_size PURPOSE Determine the version and encoded size to use for encoding hyperslab selection info USAGE hssize_t H5S__hyper_get_version_enc_size(space, block_count, version, enc_size) const H5S_t *space: IN: The dataspace hsize_t block_count: IN: The number of blocks in the selection uint32_t *version: OUT: The version to use for encoding uint8_t *enc_size: OUT: The encoded size to use RETURNS The version and the size to encode hyperslab selection info DESCRIPTION Determine the version to use for encoding hyperslab selection info based on the following: (1) the file format setting in fapl (2) whether the number of blocks or selection high bounds exceeds H5S_UINT32_MAX or not Determine the encoded size based on version: For version 3, the encoded size is determined according to: (a) regular hyperslab (1) The maximum needed to store start/stride/count/block (2) Special handling for count/block: need to provide room for H5S_UNLIMITED (b) irregular hyperslab The maximum size needed to store: (1) the number of blocks (2) the selection high bounds GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_get_version_enc_size(const H5S_t *space, hsize_t block_count, uint32_t *version, uint8_t *enc_size) { hsize_t bounds_start[H5S_MAX_RANK]; /* Starting coordinate of bounding box */ hsize_t bounds_end[H5S_MAX_RANK]; /* Opposite coordinate of bounding box */ hbool_t count_up_version = FALSE; /* Whether number of blocks exceed H5S_UINT32_MAX */ hbool_t bound_up_version = FALSE; /* Whether high bounds exceed H5S_UINT32_MAX */ H5F_libver_t low_bound; /* The 'low' bound of library format versions */ H5F_libver_t high_bound; /* The 'high' bound of library format versions */ htri_t is_regular; /* A regular hyperslab or not */ uint32_t tmp_version; /* Local temporay version */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Get bounding box for the selection */ HDmemset(bounds_end, 0, sizeof(bounds_end)); if (space->select.sel_info.hslab->unlim_dim < 0) /* ! H5S_UNLIMITED */ /* Get bounding box for the selection */ if (H5S__hyper_bounds(space, bounds_start, bounds_end) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get selection bounds") /* Determine whether the number of blocks or the high bounds in the selection exceed (2^32 - 1) */ if (block_count > H5S_UINT32_MAX) count_up_version = TRUE; else { for (u = 0; u < space->extent.rank; u++) if (bounds_end[u] > H5S_UINT32_MAX) { bound_up_version = TRUE; break; } /* end if */ } /* end else */ /* Get the file's low_bound and high_bound */ if (H5CX_get_libver_bounds(&low_bound, &high_bound) < 0) HGOTO_ERROR(H5E_DATASET, H5E_CANTGET, FAIL, "can't get low/high bounds from API context") /* Determine regular hyperslab */ is_regular = H5S__hyper_is_regular(space); if (low_bound >= H5F_LIBVER_V112 || space->select.sel_info.hslab->unlim_dim >= 0) tmp_version = MAX(H5S_HYPER_VERSION_2, H5O_sds_hyper_ver_bounds[low_bound]); else { if (count_up_version || bound_up_version) tmp_version = is_regular ? H5S_HYPER_VERSION_2 : H5S_HYPER_VERSION_3; else tmp_version = (is_regular && block_count >= 4) ? H5O_sds_hyper_ver_bounds[low_bound] : H5S_HYPER_VERSION_1; } /* end else */ /* Version bounds check */ if (tmp_version > H5O_sds_hyper_ver_bounds[high_bound]) { /* Fail for irregular hyperslab if exceeds 32 bits */ if (count_up_version) HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "The number of blocks in hyperslab selection exceeds 2^32") else if (bound_up_version) HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "The end of bounding box in hyperslab selection exceeds 2^32") else HGOTO_ERROR(H5E_DATASPACE, H5E_BADRANGE, FAIL, "Dataspace hyperslab selection version out of bounds") } /* end if */ /* Set the message version */ *version = tmp_version; /* Determine the encoded size based on version */ switch (tmp_version) { case H5S_HYPER_VERSION_1: *enc_size = H5S_SELECT_INFO_ENC_SIZE_4; break; case H5S_HYPER_VERSION_2: *enc_size = H5S_SELECT_INFO_ENC_SIZE_8; break; case H5S_HYPER_VERSION_3: if (is_regular) { uint8_t enc1, enc2; hsize_t max1 = 0; hsize_t max2 = 0; /* Find max for count[] and block[] */ for (u = 0; u < space->extent.rank; u++) { if (space->select.sel_info.hslab->diminfo.opt[u].count != H5S_UNLIMITED && space->select.sel_info.hslab->diminfo.opt[u].count > max1) max1 = space->select.sel_info.hslab->diminfo.opt[u].count; if (space->select.sel_info.hslab->diminfo.opt[u].block != H5S_UNLIMITED && space->select.sel_info.hslab->diminfo.opt[u].block > max1) max1 = space->select.sel_info.hslab->diminfo.opt[u].block; } /* end for */ /* +1 to provide room for H5S_UNLIMITED */ enc1 = H5S__hyper_get_enc_size_real(++max1); /* Find max for start[] and stride[] */ for (u = 0; u < space->extent.rank; u++) { if (space->select.sel_info.hslab->diminfo.opt[u].start > max2) max2 = space->select.sel_info.hslab->diminfo.opt[u].start; if (space->select.sel_info.hslab->diminfo.opt[u].stride > max2) max2 = space->select.sel_info.hslab->diminfo.opt[u].stride; } /* end for */ /* Determine the encoding size */ enc2 = H5S__hyper_get_enc_size_real(max2); *enc_size = (uint8_t)MAX(enc1, enc2); } /* end if */ else { hsize_t max_size = block_count; HDassert(space->select.sel_info.hslab->unlim_dim < 0); /* Find max for block_count and bounds_end[] */ for (u = 0; u < space->extent.rank; u++) if (bounds_end[u] > max_size) max_size = bounds_end[u]; /* Determine the encoding size */ *enc_size = H5S__hyper_get_enc_size_real(max_size); } /* end else */ break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown hyperslab selection version") break; } done: FUNC_LEAVE_NOAPI(ret_value) } /* H5S__hyper_get_version_enc_size() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_serial_size PURPOSE Determine the number of bytes needed to store the serialized hyperslab selection information. USAGE hssize_t H5S__hyper_serial_size(space) H5S_t *space; IN: Dataspace pointer to query RETURNS The number of bytes required on success, negative on an error. DESCRIPTION Determines the number of bytes required to serialize the current hyperslab selection information for storage on disk. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hssize_t H5S__hyper_serial_size(const H5S_t *space) { hsize_t block_count = 0; /* block counter for regular hyperslabs */ uint32_t version; /* Version number */ uint8_t enc_size; /* Encoded size of hyperslab selection info */ hssize_t ret_value = -1; /* return value */ FUNC_ENTER_STATIC HDassert(space); /* Determine the number of blocks */ if (space->select.sel_info.hslab->unlim_dim < 0) /* ! H5S_UNLIMITED */ block_count = H5S__get_select_hyper_nblocks(space, FALSE); /* Determine the version and the encoded size */ if (H5S__hyper_get_version_enc_size(space, block_count, &version, &enc_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't determine hyper version & enc_size") if (version == H5S_HYPER_VERSION_3) { /* Version 3: regular */ /* Size required is always: * <type (4 bytes)> + <version (4 bytes)> + <flags (1 byte)> + * <size of offset info (1 byte)> + <rank (4 bytes)> + * (4 (start/stride/count/block) * <enc_size> * <rank>) = * 14 + (4 * enc_size * rank) bytes */ if (H5S__hyper_is_regular(space)) ret_value = (hssize_t)14 + ((hssize_t)4 * (hssize_t)enc_size * (hssize_t)space->extent.rank); else { /* Version 3: irregular */ /* Size required is always: * <type (4 bytes)> + <version (4 bytes)> + <flags (1 byte)> + * <size of offset info (1 byte)> + <rank (4 bytes)> + * < # of blocks (depend on enc_size) > + * (2 (starting/ending offset) * <rank> * <enc_size> * <# of blocks) = * = 14 bytes + enc_size (block_count) + (2 * enc_size * rank * block_count) bytes */ ret_value = 14 + enc_size; H5_CHECK_OVERFLOW(((unsigned)2 * enc_size * space->extent.rank * block_count), hsize_t, hssize_t); ret_value += (hssize_t)((unsigned)2 * enc_size * space->extent.rank * block_count); } /* end else */ } /* end if */ else if (version == H5S_HYPER_VERSION_2) { /* Version 2 */ /* Size required is always: * <type (4 bytes)> + <version (4 bytes)> + <flags (1 byte)> + * <length (4 bytes)> + <rank (4 bytes)> + * (4 (start/stride/count/block) * <enc_size (8 bytes)> * <rank>) = * 17 + (4 * 8 * rank) bytes */ HDassert(enc_size == 8); ret_value = (hssize_t)17 + ((hssize_t)4 * (hssize_t)8 * (hssize_t)space->extent.rank); } else { HDassert(version == H5S_HYPER_VERSION_1); HDassert(enc_size == 4); /* Version 1 */ /* Basic number of bytes required to serialize hyperslab selection: * <type (4 bytes)> + <version (4 bytes)> + <padding (4 bytes)> + * <length (4 bytes)> + <rank (4 bytes)> + <# of blocks (4 bytes)> + * (2 (starting/ending offset) * <enc_size (4 bytes)> * <rank> * <# of blocks) = * = 24 bytes + (2 * 4 * rank * block_count) */ ret_value = 24; H5_CHECK_OVERFLOW((8 * space->extent.rank * block_count), hsize_t, hssize_t); ret_value += (hssize_t)(8 * space->extent.rank * block_count); } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_serial_size() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_serialize_helper PURPOSE Serialize the current selection into a user-provided buffer. USAGE void H5S__hyper_serialize_helper(spans, start, end, rank, enc_size, buf) H5S_hyper_span_info_t *spans; IN: Hyperslab span tree to serialize hssize_t start[]; IN/OUT: Accumulated start points hssize_t end[]; IN/OUT: Accumulated end points hsize_t rank; IN: Current rank looking at uint8_t enc_size IN: Encoded size of hyperslab selection info uint8_t *buf; OUT: Buffer to put serialized selection into RETURNS None DESCRIPTION Serializes the current element selection into a buffer. (Primarily for storing on disk). GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_serialize_helper(const H5S_hyper_span_info_t *spans, hsize_t *start, hsize_t *end, hsize_t rank, uint8_t enc_size, uint8_t **p) { H5S_hyper_span_t *curr; /* Pointer to current hyperslab span */ uint8_t * pp = (*p); /* Local pointer for decoding */ FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(spans); HDassert(start); HDassert(end); HDassert(rank < H5S_MAX_RANK); HDassert(p && pp); /* Walk through the list of spans, recursing or outputting them */ curr = spans->head; while (curr != NULL) { /* Recurse if this node has down spans */ if (curr->down != NULL) { /* Add the starting and ending points for this span to the list */ start[rank] = curr->low; end[rank] = curr->high; /* Recurse down to the next dimension */ H5S__hyper_serialize_helper(curr->down, start, end, rank + 1, enc_size, &pp); } /* end if */ else { hsize_t u; /* Index variable */ /* Encode all the previous dimensions starting & ending points */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: /* Encode previous starting points */ for (u = 0; u < rank; u++) UINT16ENCODE(pp, (uint16_t)start[u]); /* Encode starting point for this span */ UINT16ENCODE(pp, (uint16_t)curr->low); /* Encode previous ending points */ for (u = 0; u < rank; u++) UINT16ENCODE(pp, (uint16_t)end[u]); /* Encode starting point for this span */ UINT16ENCODE(pp, (uint16_t)curr->high); break; case H5S_SELECT_INFO_ENC_SIZE_4: /* Encode previous starting points */ for (u = 0; u < rank; u++) UINT32ENCODE(pp, (uint32_t)start[u]); /* Encode starting point for this span */ UINT32ENCODE(pp, (uint32_t)curr->low); /* Encode previous ending points */ for (u = 0; u < rank; u++) UINT32ENCODE(pp, (uint32_t)end[u]); /* Encode starting point for this span */ UINT32ENCODE(pp, (uint32_t)curr->high); break; case H5S_SELECT_INFO_ENC_SIZE_8: /* Encode previous starting points */ for (u = 0; u < rank; u++) UINT64ENCODE(pp, (uint64_t)start[u]); /* Encode starting point for this span */ UINT64ENCODE(pp, (uint64_t)curr->low); /* Encode previous ending points */ for (u = 0; u < rank; u++) UINT64ENCODE(pp, (uint64_t)end[u]); /* Encode starting point for this span */ UINT64ENCODE(pp, (uint64_t)curr->high); break; default: HDassert(0 && "Unknown enc size?!?"); } /* end switch */ } /* end else */ /* Advance to next node */ curr = curr->next; } /* end while */ /* Update encoding pointer */ *p = pp; FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_serialize_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_serialize PURPOSE Serialize the current selection into a user-provided buffer. USAGE herr_t H5S__hyper_serialize(space, p) const H5S_t *space; IN: Dataspace with selection to serialize uint8_t **p; OUT: Pointer to buffer to put serialized selection. Will be advanced to end of serialized selection. RETURNS Non-negative on success/Negative on failure DESCRIPTION Serializes the current element selection into a buffer. (Primarily for storing on disk). GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_serialize(const H5S_t *space, uint8_t **p) { const H5S_hyper_dim_t *diminfo; /* Alias for dataspace's diminfo information */ hsize_t tmp_count[H5S_MAX_RANK]; /* Temporary hyperslab counts */ hsize_t offset[H5S_MAX_RANK]; /* Offset of element in dataspace */ hsize_t start[H5S_MAX_RANK]; /* Location of start of hyperslab */ hsize_t end[H5S_MAX_RANK]; /* Location of end of hyperslab */ uint8_t * pp; /* Local pointer for encoding */ uint8_t * lenp = NULL; /* pointer to length location for later storage */ uint32_t len = 0; /* number of bytes used */ uint32_t version; /* Version number */ uint8_t flags = 0; /* Flags for message */ hsize_t block_count = 0; /* block counter for regular hyperslabs */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned ndims; /* Rank of the dataspace */ unsigned u; /* Local counting variable */ hbool_t complete = FALSE; /* Whether we are done with the iteration */ hbool_t is_regular; /* Whether selection is regular */ uint8_t enc_size; /* Encoded size */ herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_STATIC /* Sanity checks */ HDassert(space); HDassert(p); pp = (*p); HDassert(pp); /* Set some convienence values */ ndims = space->extent.rank; diminfo = space->select.sel_info.hslab->diminfo.opt; /* Calculate the # of blocks */ if (space->select.sel_info.hslab->unlim_dim < 0) /* ! H5S_UNLIMITED */ block_count = H5S__get_select_hyper_nblocks(space, FALSE); /* Determine the version and the encoded size */ if (H5S__hyper_get_version_enc_size(space, block_count, &version, &enc_size) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't determine hyper version & enc_size") is_regular = H5S__hyper_is_regular(space); if (is_regular && (version == H5S_HYPER_VERSION_2 || version == H5S_HYPER_VERSION_3)) flags |= H5S_HYPER_REGULAR; /* Store the preamble information */ UINT32ENCODE(pp, (uint32_t)H5S_GET_SELECT_TYPE(space)); /* Store the type of selection */ UINT32ENCODE(pp, version); /* Store the version number */ if (version >= 3) { *(pp)++ = flags; /* Store the flags */ *(pp)++ = enc_size; /* Store size of offset info */ } /* end if */ else { if (version == 2) *(pp)++ = flags; /* Store the flags */ else UINT32ENCODE(pp, (uint32_t)0); /* Store the un-used padding */ lenp = pp; /* keep the pointer to the length location for later */ pp += 4; /* skip over space for length */ len += 4; /* ndims */ } /* end else */ /* Encode number of dimensions */ UINT32ENCODE(pp, (uint32_t)ndims); if (is_regular) { if (version >= H5S_HYPER_VERSION_2) { HDassert(H5S_UNLIMITED == HSIZE_UNDEF); /* Iterate over dimensions */ /* Encode start/stride/block/count */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: HDassert(version == H5S_HYPER_VERSION_3); for (u = 0; u < space->extent.rank; u++) { UINT16ENCODE(pp, diminfo[u].start); UINT16ENCODE(pp, diminfo[u].stride); if (diminfo[u].count == H5S_UNLIMITED) UINT16ENCODE(pp, H5S_UINT16_MAX) else UINT16ENCODE(pp, diminfo[u].count) if (diminfo[u].block == H5S_UNLIMITED) UINT16ENCODE(pp, H5S_UINT16_MAX) else UINT16ENCODE(pp, diminfo[u].block) } /* end for */ break; case H5S_SELECT_INFO_ENC_SIZE_4: HDassert(version == H5S_HYPER_VERSION_3); for (u = 0; u < space->extent.rank; u++) { UINT32ENCODE(pp, diminfo[u].start); UINT32ENCODE(pp, diminfo[u].stride); if (diminfo[u].count == H5S_UNLIMITED) UINT32ENCODE(pp, H5S_UINT32_MAX) else UINT32ENCODE(pp, diminfo[u].count) if (diminfo[u].block == H5S_UNLIMITED) UINT32ENCODE(pp, H5S_UINT32_MAX) else UINT32ENCODE(pp, diminfo[u].block) } /* end for */ break; case H5S_SELECT_INFO_ENC_SIZE_8: HDassert(version == H5S_HYPER_VERSION_2 || version == H5S_HYPER_VERSION_3); for (u = 0; u < space->extent.rank; u++) { UINT64ENCODE(pp, diminfo[u].start); UINT64ENCODE(pp, diminfo[u].stride); if (diminfo[u].count == H5S_UNLIMITED) UINT64ENCODE(pp, H5S_UINT64_MAX) else UINT64ENCODE(pp, diminfo[u].count) if (diminfo[u].block == H5S_UNLIMITED) UINT64ENCODE(pp, H5S_UINT64_MAX) else UINT64ENCODE(pp, diminfo[u].block) } /* end for */ if (version == H5S_HYPER_VERSION_2) len += (4 * space->extent.rank * 8); break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown offset info size for hyperslab") break; } /* end switch */ } /* end if */ else { HDassert(version == H5S_HYPER_VERSION_1); /* Set some convienence values */ fast_dim = ndims - 1; /* Encode number of hyperslabs */ H5_CHECK_OVERFLOW(block_count, hsize_t, uint32_t); UINT32ENCODE(pp, (uint32_t)block_count); len += 4; /* Now serialize the information for the regular hyperslab */ /* Build the tables of count sizes as well as the initial offset */ for (u = 0; u < ndims; u++) { tmp_count[u] = diminfo[u].count; offset[u] = diminfo[u].start; } /* end for */ /* Go iterate over the hyperslabs */ while (complete == FALSE) { /* Iterate over the blocks in the fastest dimension */ while (tmp_count[fast_dim] > 0) { /* Add 8 bytes times the rank for each hyperslab selected */ len += 8 * ndims; /* Encode hyperslab starting location */ for (u = 0; u < ndims; u++) UINT32ENCODE(pp, (uint32_t)offset[u]); /* Encode hyperslab ending location */ for (u = 0; u < ndims; u++) UINT32ENCODE(pp, (uint32_t)(offset[u] + (diminfo[u].block - 1))); /* Move the offset to the next sequence to start */ offset[fast_dim] += diminfo[fast_dim].stride; /* Decrement the block count */ tmp_count[fast_dim]--; } /* end while */ /* Work on other dimensions if necessary */ if (fast_dim > 0) { int temp_dim; /* Temporary rank holder */ /* Reset the block counts */ tmp_count[fast_dim] = diminfo[fast_dim].count; /* Bubble up the decrement to the slower changing dimensions */ temp_dim = (int)fast_dim - 1; while (temp_dim >= 0 && complete == FALSE) { /* Decrement the block count */ tmp_count[temp_dim]--; /* Check if we have more blocks left */ if (tmp_count[temp_dim] > 0) break; /* Check for getting out of iterator */ if (temp_dim == 0) complete = TRUE; /* Reset the block count in this dimension */ tmp_count[temp_dim] = diminfo[temp_dim].count; /* Wrapped a dimension, go up to next dimension */ temp_dim--; } /* end while */ } /* end if */ else break; /* Break out now, for 1-D selections */ /* Re-compute offset array */ for (u = 0; u < ndims; u++) offset[u] = diminfo[u].start + diminfo[u].stride * (diminfo[u].count - tmp_count[u]); } /* end while */ } /* end else */ } /* end if */ else { /* irregular */ /* Encode number of hyperslabs */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: HDassert(version == H5S_HYPER_VERSION_3); H5_CHECK_OVERFLOW(block_count, hsize_t, uint16_t); UINT16ENCODE(pp, (uint16_t)block_count); break; case H5S_SELECT_INFO_ENC_SIZE_4: HDassert(version == H5S_HYPER_VERSION_1 || version == H5S_HYPER_VERSION_3); H5_CHECK_OVERFLOW(block_count, hsize_t, uint32_t); UINT32ENCODE(pp, (uint32_t)block_count); break; case H5S_SELECT_INFO_ENC_SIZE_8: HDassert(version == H5S_HYPER_VERSION_3); UINT64ENCODE(pp, block_count); break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown offset info size for hyperslab") break; } /* end switch */ if (version == H5S_HYPER_VERSION_1) { len += 4; /* block_count */ /* Add 8 bytes times the rank for each hyperslab selected */ H5_CHECK_OVERFLOW((8 * ndims * block_count), hsize_t, size_t); len += (uint32_t)(8 * ndims * block_count); } /* end if */ H5S__hyper_serialize_helper(space->select.sel_info.hslab->span_lst, start, end, (hsize_t)0, enc_size, &pp); } /* end else */ /* Encode length */ if (version <= H5S_HYPER_VERSION_2) UINT32ENCODE(lenp, (uint32_t)len); /* Store the length of the extra information */ /* Update encoding pointer */ *p = pp; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_serialize() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_deserialize PURPOSE Deserialize the current selection from a user-provided buffer. USAGE herr_t H5S__hyper_deserialize(space, p) H5S_t **space; IN/OUT: Dataspace pointer to place selection into uint8 **p; OUT: Pointer to buffer holding serialized selection. Will be advanced to end of serialized selection. RETURNS Non-negative on success/Negative on failure DESCRIPTION Deserializes the current selection into a buffer. (Primarily for retrieving from disk). GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_deserialize(H5S_t **space, const uint8_t **p) { H5S_t *tmp_space = NULL; /* Pointer to actual dataspace to use, either *space or a newly allocated one */ hsize_t dims[H5S_MAX_RANK]; /* Dimenion sizes */ hsize_t start[H5S_MAX_RANK]; /* hyperslab start information */ hsize_t block[H5S_MAX_RANK]; /* hyperslab block information */ uint32_t version; /* Version number */ uint8_t flags = 0; /* Flags */ uint8_t enc_size = 0; /* Encoded size of selection info */ unsigned rank; /* rank of points */ const uint8_t *pp; /* Local pointer for decoding */ unsigned u; /* Local counting variable */ herr_t ret_value = FAIL; /* return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(p); pp = (*p); HDassert(pp); /* As part of the efforts to push all selection-type specific coding to the callbacks, the coding for the allocation of a null dataspace is moved from H5S_select_deserialize() in H5Sselect.c to here. This is needed for decoding virtual layout in H5O__layout_decode() */ /* Allocate space if not provided */ if (!*space) { if (NULL == (tmp_space = H5S_create(H5S_SIMPLE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, FAIL, "can't create dataspace") } /* end if */ else tmp_space = *space; /* Decode version */ UINT32DECODE(pp, version); if (version < H5S_HYPER_VERSION_1 || version > H5S_HYPER_VERSION_LATEST) HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "bad version number for hyperslab selection") if (version >= (uint32_t)H5S_HYPER_VERSION_2) { /* Decode flags */ flags = *(pp)++; if (version >= (uint32_t)H5S_HYPER_VERSION_3) /* decode size of offset info */ enc_size = *(pp)++; else { /* Skip over the remainder of the header */ pp += 4; enc_size = H5S_SELECT_INFO_ENC_SIZE_8; } /* end else */ /* Check for unknown flags */ if (flags & ~H5S_SELECT_FLAG_BITS) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTLOAD, FAIL, "unknown flag for selection") } else { /* Skip over the remainder of the header */ pp += 8; enc_size = H5S_SELECT_INFO_ENC_SIZE_4; } /* end else */ /* Check encoded */ if (enc_size & ~H5S_SELECT_INFO_ENC_SIZE_BITS) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTLOAD, FAIL, "unknown size of point/offset info for selection") /* Decode the rank of the point selection */ UINT32DECODE(pp, rank); if (!*space) { /* Patch the rank of the allocated dataspace */ HDmemset(dims, 0, (size_t)rank * sizeof(dims[0])); if (H5S_set_extent_simple(tmp_space, rank, dims, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "can't set dimensions") } /* end if */ else /* Verify the rank of the provided dataspace */ if (rank != tmp_space->extent.rank) HGOTO_ERROR(H5E_DATASPACE, H5E_BADRANGE, FAIL, "rank of serialized selection does not match dataspace") if (flags & H5S_HYPER_REGULAR) { hsize_t stride[H5S_MAX_RANK]; /* Hyperslab stride information */ hsize_t count[H5S_MAX_RANK]; /* Hyperslab count information */ /* Sanity checks */ HDassert(H5S_UNLIMITED == HSIZE_UNDEF); HDassert(version >= H5S_HYPER_VERSION_2); /* Decode start/stride/block/count */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: for (u = 0; u < tmp_space->extent.rank; u++) { UINT16DECODE(pp, start[u]); UINT16DECODE(pp, stride[u]); UINT16DECODE(pp, count[u]); if ((uint16_t)count[u] == H5S_UINT16_MAX) count[u] = H5S_UNLIMITED; UINT16DECODE(pp, block[u]); if ((uint16_t)block[u] == H5S_UINT16_MAX) block[u] = H5S_UNLIMITED; } /* end for */ break; case H5S_SELECT_INFO_ENC_SIZE_4: for (u = 0; u < tmp_space->extent.rank; u++) { UINT32DECODE(pp, start[u]); UINT32DECODE(pp, stride[u]); UINT32DECODE(pp, count[u]); if ((uint32_t)count[u] == H5S_UINT32_MAX) count[u] = H5S_UNLIMITED; UINT32DECODE(pp, block[u]); if ((uint32_t)block[u] == H5S_UINT32_MAX) block[u] = H5S_UNLIMITED; } /* end for */ break; case H5S_SELECT_INFO_ENC_SIZE_8: for (u = 0; u < tmp_space->extent.rank; u++) { UINT64DECODE(pp, start[u]); UINT64DECODE(pp, stride[u]); UINT64DECODE(pp, count[u]); if ((uint64_t)count[u] == H5S_UINT64_MAX) count[u] = H5S_UNLIMITED; UINT64DECODE(pp, block[u]); if ((uint64_t)block[u] == H5S_UINT64_MAX) block[u] = H5S_UNLIMITED; } /* end for */ break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown offset info size for hyperslab") break; } /* end switch */ /* Select the hyperslab to the current selection */ if ((ret_value = H5S_select_hyperslab(tmp_space, H5S_SELECT_SET, start, stride, count, block)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't change selection") } /* end if */ else { const hsize_t *stride; /* Hyperslab stride information */ const hsize_t *count; /* Hyperslab count information */ hsize_t end[H5S_MAX_RANK]; /* Hyperslab end information */ hsize_t * tstart; /* Temporary hyperslab pointers */ hsize_t * tend; /* Temporary hyperslab pointers */ hsize_t * tblock; /* Temporary hyperslab pointers */ size_t num_elem; /* Number of elements in selection */ unsigned v; /* Local counting variable */ /* Decode the number of blocks */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: UINT16DECODE(pp, num_elem); break; case H5S_SELECT_INFO_ENC_SIZE_4: UINT32DECODE(pp, num_elem); break; case H5S_SELECT_INFO_ENC_SIZE_8: UINT64DECODE(pp, num_elem); break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown offset info size for hyperslab") break; } /* end switch */ /* Set the count & stride for all blocks */ stride = count = H5S_hyper_ones_g; /* Retrieve the coordinates from the buffer */ for (u = 0; u < num_elem; u++) { /* Decode the starting and ending points */ switch (enc_size) { case H5S_SELECT_INFO_ENC_SIZE_2: for (tstart = start, v = 0; v < rank; v++, tstart++) UINT16DECODE(pp, *tstart); for (tend = end, v = 0; v < rank; v++, tend++) UINT16DECODE(pp, *tend); break; case H5S_SELECT_INFO_ENC_SIZE_4: for (tstart = start, v = 0; v < rank; v++, tstart++) UINT32DECODE(pp, *tstart); for (tend = end, v = 0; v < rank; v++, tend++) UINT32DECODE(pp, *tend); break; case H5S_SELECT_INFO_ENC_SIZE_8: for (tstart = start, v = 0; v < rank; v++, tstart++) UINT64DECODE(pp, *tstart); for (tend = end, v = 0; v < rank; v++, tend++) UINT64DECODE(pp, *tend); break; default: HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unknown offset info size for hyperslab") break; } /* end switch */ /* Change the ending points into blocks */ for (tblock = block, tstart = start, tend = end, v = 0; v < rank; v++, tstart++, tend++, tblock++) *tblock = (*tend - *tstart) + 1; /* Select or add the hyperslab to the current selection */ if ((ret_value = H5S_select_hyperslab(tmp_space, (u == 0 ? H5S_SELECT_SET : H5S_SELECT_OR), start, stride, count, block)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't change selection") } /* end for */ } /* end else */ /* Update decoding pointer */ *p = pp; /* Return space to the caller if allocated */ if (!*space) *space = tmp_space; done: /* Free temporary space if not passed to caller (only happens on error) */ if (!*space && tmp_space) if (H5S_close(tmp_space) < 0) HDONE_ERROR(H5E_DATASPACE, H5E_CANTFREE, FAIL, "can't close dataspace") FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_deserialize() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_span_blocklist PURPOSE Get a list of hyperslab blocks currently selected USAGE herr_t H5S__hyper_span_blocklist(spans, start, end, rank, startblock, numblocks, buf) H5S_hyper_span_info_t *spans; IN: Dataspace pointer of selection to query hsize_t start[]; IN/OUT: Accumulated start points hsize_t end[]; IN/OUT: Accumulated end points hsize_t rank; IN: Rank of dataspace hsize_t *startblock; IN/OUT: Hyperslab block to start with hsize_t *numblocks; IN/OUT: Number of hyperslab blocks to get hsize_t **buf; OUT: List of hyperslab blocks selected RETURNS Non-negative on success/Negative on failure DESCRIPTION Puts a list of the hyperslab blocks into the user's buffer. The blocks start with the '*startblock'th block in the list of blocks and put '*numblocks' number of blocks into the user's buffer (or until the end of the list of blocks, whichever happens first) The block coordinates have the same dimensionality (rank) as the dataspace they are located within. The list of blocks is formatted as follows: <"start" coordinate> immediately followed by <"opposite" corner coordinate>, followed by the next "start" and "opposite" coordinate, etc. until all the block information requested has been put into the user's buffer. No guarantee of any order of the blocks is implied. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_span_blocklist(const H5S_hyper_span_info_t *spans, hsize_t start[], hsize_t end[], hsize_t rank, hsize_t *startblock, hsize_t *numblocks, hsize_t **buf) { const H5S_hyper_span_t *curr; /* Pointer to current hyperslab span */ herr_t ret_value = SUCCEED; /* return value */ FUNC_ENTER_STATIC /* Sanity checks */ HDassert(spans); HDassert(rank < H5S_MAX_RANK); HDassert(start); HDassert(end); HDassert(startblock); HDassert(numblocks && *numblocks > 0); HDassert(buf && *buf); /* Walk through the list of spans, recursing or outputting them */ curr = spans->head; while (curr != NULL && *numblocks > 0) { /* Recurse if this node has down spans */ if (curr->down != NULL) { /* Add the starting and ending points for this span to the list */ start[rank] = curr->low; end[rank] = curr->high; /* Recurse down to the next dimension */ if (H5S__hyper_span_blocklist(curr->down, start, end, (rank + 1), startblock, numblocks, buf) < 0) HGOTO_ERROR(H5E_INTERNAL, H5E_CANTFREE, FAIL, "failed to release hyperslab spans") } /* end if */ else { /* Skip this block if we haven't skipped all the startblocks yet */ if (*startblock > 0) { /* Decrement the starting block */ (*startblock)--; } /* end if */ /* Process this block */ else { /* Encode all the previous dimensions starting & ending points */ /* Copy previous starting points */ H5MM_memcpy(*buf, start, rank * sizeof(hsize_t)); (*buf) += rank; /* Copy starting point for this span */ **buf = curr->low; (*buf)++; /* Copy previous ending points */ H5MM_memcpy(*buf, end, rank * sizeof(hsize_t)); (*buf) += rank; /* Copy ending point for this span */ **buf = curr->high; (*buf)++; /* Decrement the number of blocks processed */ (*numblocks)--; } /* end else */ } /* end else */ /* Advance to next node */ curr = curr->next; } /* end while */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_span_blocklist() */ /*-------------------------------------------------------------------------- NAME H5S__get_select_hyper_blocklist PURPOSE Get the list of hyperslab blocks currently selected USAGE herr_t H5S__get_select_hyper_blocklist(space, startblock, numblocks, buf) H5S_t *space; IN: Dataspace pointer of selection to query hsize_t startblock; IN: Hyperslab block to start with hsize_t numblocks; IN: Number of hyperslab blocks to get hsize_t *buf; OUT: List of hyperslab blocks selected RETURNS Non-negative on success, negative on failure DESCRIPTION Puts a list of the hyperslab blocks into the user's buffer. The blocks start with the 'startblock'th block in the list of blocks and put 'numblocks' number of blocks into the user's buffer (or until the end of the list of blocks, whichever happens first) The block coordinates have the same dimensionality (rank) as the dataspace they are located within. The list of blocks is formatted as follows: <"start" coordinate> immediately followed by <"opposite" corner coordinate>, followed by the next "start" and "opposite" coordinate, etc. until all the block information requested has been put into the user's buffer. No guarantee of any order of the blocks is implied. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__get_select_hyper_blocklist(H5S_t *space, hsize_t startblock, hsize_t numblocks, hsize_t *buf) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC_NOERR HDassert(space); HDassert(buf); HDassert(space->select.sel_info.hslab->unlim_dim < 0); /* Attempt to rebuild diminfo if it is invalid and has not been confirmed * to be impossible. */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild(space); /* Check for a "regular" hyperslab selection */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { const H5S_hyper_dim_t *diminfo; /* Alias for dataspace's diminfo information */ hsize_t tmp_count[H5S_MAX_RANK]; /* Temporary hyperslab counts */ hsize_t offset[H5S_MAX_RANK]; /* Offset of element in dataspace */ hsize_t end[H5S_MAX_RANK]; /* End of elements in dataspace */ unsigned fast_dim; /* Rank of the fastest changing dimension for the dataspace */ unsigned ndims; /* Rank of the dataspace */ hbool_t done; /* Whether we are done with the iteration */ unsigned u; /* Counter */ /* Set some convienence values */ ndims = space->extent.rank; fast_dim = ndims - 1; /* Check which set of dimension information to use */ if (space->select.sel_info.hslab->unlim_dim >= 0) /* * There is an unlimited dimension so we must use diminfo.opt as * it has been "clipped" to the current extent. */ diminfo = space->select.sel_info.hslab->diminfo.opt; else /* * Use the "application dimension information" to pass back to * the user the blocks they set, not the optimized, internal * information. */ diminfo = space->select.sel_info.hslab->diminfo.app; /* Build the tables of count sizes as well as the initial offset */ for (u = 0; u < ndims; u++) { tmp_count[u] = diminfo[u].count; offset[u] = diminfo[u].start; end[u] = diminfo[u].start + (diminfo[u].block - 1); } /* end for */ /* We're not done with the iteration */ done = FALSE; /* Go iterate over the hyperslabs */ while (!done && numblocks > 0) { /* Skip over initial blocks */ if (startblock > 0) { /* Skip all blocks in row */ if (startblock >= tmp_count[fast_dim]) { startblock -= tmp_count[fast_dim]; tmp_count[fast_dim] = 0; } /* end if */ else { /* Move the offset to the next sequence to start */ offset[fast_dim] += diminfo[fast_dim].stride * startblock; end[fast_dim] += diminfo[fast_dim].stride * startblock; /* Decrement the block count */ tmp_count[fast_dim] -= startblock; /* Done with starting blocks */ startblock = 0; } /* end else */ } /* end if */ /* Iterate over the blocks in the fastest dimension */ while (tmp_count[fast_dim] > 0 && numblocks > 0) { /* Sanity check */ HDassert(startblock == 0); /* Copy the starting location */ H5MM_memcpy(buf, offset, sizeof(hsize_t) * ndims); buf += ndims; /* Compute the ending location */ H5MM_memcpy(buf, end, sizeof(hsize_t) * ndims); buf += ndims; /* Decrement the number of blocks to retrieve */ numblocks--; /* Move the offset to the next sequence to start */ offset[fast_dim] += diminfo[fast_dim].stride; end[fast_dim] += diminfo[fast_dim].stride; /* Decrement the block count */ tmp_count[fast_dim]--; } /* end while */ /* Work on other dimensions if necessary */ if (fast_dim > 0 && numblocks > 0) { int temp_dim; /* Temporary rank holder */ /* Reset the block counts */ tmp_count[fast_dim] = diminfo[fast_dim].count; /* Bubble up the decrement to the slower changing dimensions */ temp_dim = (int)(fast_dim - 1); while (temp_dim >= 0 && !done) { /* Decrement the block count */ tmp_count[temp_dim]--; /* Check if we have more blocks left */ if (tmp_count[temp_dim] > 0) break; /* Reset the block count in this dimension */ tmp_count[temp_dim] = diminfo[temp_dim].count; /* Check for getting out of iterator */ if (temp_dim == 0) done = TRUE; /* Wrapped a dimension, go up to next dimension */ temp_dim--; } /* end while */ } /* end if */ /* Re-compute offset & end arrays */ if (!done) for (u = 0; u < ndims; u++) { offset[u] = diminfo[u].start + diminfo[u].stride * (diminfo[u].count - tmp_count[u]); end[u] = offset[u] + (diminfo[u].block - 1); } /* end for */ } /* end while */ } /* end if */ else { hsize_t start[H5S_MAX_RANK]; /* Location of start of hyperslab */ hsize_t end[H5S_MAX_RANK]; /* Location of end of hyperslab */ ret_value = H5S__hyper_span_blocklist(space->select.sel_info.hslab->span_lst, start, end, (hsize_t)0, &startblock, &numblocks, &buf); } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__get_select_hyper_blocklist() */ /*-------------------------------------------------------------------------- NAME H5Sget_select_hyper_blocklist PURPOSE Get the list of hyperslab blocks currently selected USAGE herr_t H5Sget_select_hyper_blocklist(dsid, startblock, numblocks, buf) hid_t dsid; IN: Dataspace ID of selection to query hsize_t startblock; IN: Hyperslab block to start with hsize_t numblocks; IN: Number of hyperslab blocks to get hsize_t buf[]; OUT: List of hyperslab blocks selected RETURNS Non-negative on success, negative on failure DESCRIPTION Puts a list of the hyperslab blocks into the user's buffer. The blocks start with the 'startblock'th block in the list of blocks and put 'numblocks' number of blocks into the user's buffer (or until the end of the list of blocks, whichever happen first) The block coordinates have the same dimensionality (rank) as the dataspace they are located within. The list of blocks is formatted as follows: <"start" coordinate> immediately followed by <"opposite" corner coordinate>, followed by the next "start" and "opposite" coordinate, etc. until all the block information requested has been put into the user's buffer. No guarantee of any order of the blocks is implied. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5Sget_select_hyper_blocklist(hid_t spaceid, hsize_t startblock, hsize_t numblocks, hsize_t buf[/*numblocks*/] /*out*/) { H5S_t *space; /* Dataspace to modify selection of */ herr_t ret_value; /* return value */ FUNC_ENTER_API(FAIL) H5TRACE4("e", "ihhx", spaceid, startblock, numblocks, buf); /* Check args */ if (buf == NULL) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "invalid pointer") if (NULL == (space = (H5S_t *)H5I_object_verify(spaceid, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (H5S_GET_SELECT_TYPE(space) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a hyperslab selection") if (space->select.sel_info.hslab->unlim_dim >= 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "cannot get blocklist for unlimited selection") /* Go get the correct number of blocks */ if (numblocks > 0) ret_value = H5S__get_select_hyper_blocklist(space, startblock, numblocks, buf); else ret_value = SUCCEED; /* Successfully got 0 blocks... */ done: FUNC_LEAVE_API(ret_value) } /* end H5Sget_select_hyper_blocklist() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_bounds PURPOSE Gets the bounding box containing the selection. USAGE herr_t H5S__hyper_bounds(space, hsize_t *start, hsize_t *end) H5S_t *space; IN: Dataspace pointer of selection to query hsize_t *start; OUT: Starting coordinate of bounding box hsize_t *end; OUT: Opposite coordinate of bounding box RETURNS Non-negative on success, negative on failure DESCRIPTION Retrieves the bounding box containing the current selection and places it into the user's buffers. The start and end buffers must be large enough to hold the dataspace rank number of coordinates. The bounding box exactly contains the selection, ie. if a 2-D element selection is currently defined with the following points: (4,5), (6,8) (10,7), the bounding box with be (4, 5), (10, 8). The bounding box calculations _does_ include the current offset of the selection within the dataspace extent. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_bounds(const H5S_t *space, hsize_t *start, hsize_t *end) { const hsize_t *low_bounds, *high_bounds; /* Pointers to the correct pair of low & high bounds */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(space); HDassert(start); HDassert(end); /* Check which set of low & high bounds we should be using */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { low_bounds = space->select.sel_info.hslab->diminfo.low_bounds; high_bounds = space->select.sel_info.hslab->diminfo.high_bounds; } /* end if */ else { low_bounds = space->select.sel_info.hslab->span_lst->low_bounds; high_bounds = space->select.sel_info.hslab->span_lst->high_bounds; } /* end else */ /* Check for offset set */ if (space->select.offset_changed) { unsigned u; /* Local index variable */ /* Loop over dimensions */ for (u = 0; u < space->extent.rank; u++) { /* Sanity check */ HDassert(low_bounds[u] <= high_bounds[u]); /* Check for offset moving selection negative */ if (((hssize_t)low_bounds[u] + space->select.offset[u]) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADRANGE, FAIL, "offset moves selection out of bounds") /* Set the low & high bounds in this dimension */ start[u] = (hsize_t)((hssize_t)low_bounds[u] + space->select.offset[u]); if ((int)u == space->select.sel_info.hslab->unlim_dim) end[u] = H5S_UNLIMITED; else end[u] = (hsize_t)((hssize_t)high_bounds[u] + space->select.offset[u]); } /* end for */ } /* end if */ else { /* Offset vector is still zeros, just copy low & high bounds */ H5MM_memcpy(start, low_bounds, sizeof(hsize_t) * space->extent.rank); H5MM_memcpy(end, high_bounds, sizeof(hsize_t) * space->extent.rank); } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_bounds() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_offset PURPOSE Gets the linear offset of the first element for the selection. USAGE herr_t H5S__hyper_offset(space, offset) const H5S_t *space; IN: Dataspace pointer of selection to query hsize_t *offset; OUT: Linear offset of first element in selection RETURNS Non-negative on success, negative on failure DESCRIPTION Retrieves the linear offset (in "units" of elements) of the first element selected within the dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Calling this function on a "none" selection returns fail. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_offset(const H5S_t *space, hsize_t *offset) { const hssize_t *sel_offset; /* Pointer to the selection's offset */ const hsize_t * dim_size; /* Pointer to a dataspace's extent */ hsize_t accum; /* Accumulator for dimension sizes */ unsigned rank; /* Dataspace rank */ int i; /* index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC HDassert(space && space->extent.rank > 0); HDassert(offset); /* Start at linear offset 0 */ *offset = 0; /* Set up pointers to arrays of values */ rank = space->extent.rank; sel_offset = space->select.offset; dim_size = space->extent.size; /* Check for a "regular" hyperslab selection */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { const H5S_hyper_dim_t *diminfo = space->select.sel_info.hslab->diminfo.opt; /* Local alias for diminfo */ /* Loop through starting coordinates, calculating the linear offset */ accum = 1; for (i = (int)(rank - 1); i >= 0; i--) { hssize_t hyp_offset = (hssize_t)diminfo[i].start + sel_offset[i]; /* Hyperslab's offset in this dimension */ /* Check for offset moving selection out of the dataspace */ if (hyp_offset < 0 || (hsize_t)hyp_offset >= dim_size[i]) HGOTO_ERROR(H5E_DATASPACE, H5E_BADRANGE, FAIL, "offset moves selection out of bounds") /* Add the hyperslab's offset in this dimension to the total linear offset */ *offset += (hsize_t)(hyp_offset * (hssize_t)accum); /* Increase the accumulator */ accum *= dim_size[i]; } /* end for */ } /* end if */ else { const H5S_hyper_span_t *span; /* Hyperslab span node */ hsize_t dim_accum[H5S_MAX_RANK]; /* Accumulators, for each dimension */ /* Calculate the accumulator for each dimension */ accum = 1; for (i = (int)(rank - 1); i >= 0; i--) { /* Set the accumulator for this dimension */ dim_accum[i] = accum; /* Increase the accumulator */ accum *= dim_size[i]; } /* end for */ /* Get information for the first span, in the slowest changing dimension */ span = space->select.sel_info.hslab->span_lst->head; /* Work down the spans, computing the linear offset */ i = 0; while (span) { hssize_t hyp_offset = (hssize_t)span->low + sel_offset[i]; /* Hyperslab's offset in this dimension */ /* Check for offset moving selection out of the dataspace */ if (hyp_offset < 0 || (hsize_t)hyp_offset >= dim_size[i]) HGOTO_ERROR(H5E_DATASPACE, H5E_BADRANGE, FAIL, "offset moves selection out of bounds") /* Add the hyperslab's offset in this dimension to the total linear offset */ *offset += (hsize_t)(hyp_offset * (hssize_t)dim_accum[i]); /* Advance to first span in "down" dimension */ if (span->down) { HDassert(span->down->head); span = span->down->head; } /* end if */ else span = NULL; i++; } /* end while */ } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_offset() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_unlim_dim PURPOSE Return unlimited dimension of selection, or -1 if none USAGE int H5S__hyper_unlim_dim(space) H5S_t *space; IN: Dataspace pointer to check RETURNS Unlimited dimension of selection, or -1 if none (never fails). DESCRIPTION Returns the index of the unlimited dimension of the selection, or -1 if the selection has no unlimited dimension. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static int H5S__hyper_unlim_dim(const H5S_t *space) { FUNC_ENTER_STATIC_NOERR FUNC_LEAVE_NOAPI(space->select.sel_info.hslab->unlim_dim); } /* end H5S__hyper_unlim_dim() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_num_elem_non_unlim PURPOSE Return number of elements in the non-unlimited dimensions USAGE herr_t H5S__hyper_num_elem_non_unlim(space,num_elem_non_unlim) H5S_t *space; IN: Dataspace pointer to check hsize_t *num_elem_non_unlim; OUT: Number of elements in the non-unlimited dimensions RETURNS Non-negative on success/Negative on failure DESCRIPTION Returns the number of elements in a slice through the non-unlimited dimensions of the selection. Fails if the selection has no unlimited dimension. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_num_elem_non_unlim(const H5S_t *space, hsize_t *num_elem_non_unlim) { herr_t ret_value = SUCCEED; FUNC_ENTER_STATIC /* Sanity check */ HDassert(space); HDassert(num_elem_non_unlim); /* Get number of elements in the non-unlimited dimensions */ if (space->select.sel_info.hslab->unlim_dim >= 0) *num_elem_non_unlim = space->select.sel_info.hslab->num_elem_non_unlim; else HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "selection has no unlimited dimension") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_num_elem_non_unlim() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_is_contiguous PURPOSE Check if a hyperslab selection is contiguous within the dataspace extent. USAGE htri_t H5S__hyper_is_contiguous(space) H5S_t *space; IN: Dataspace pointer to check RETURNS TRUE/FALSE/FAIL DESCRIPTION Checks to see if the current selection in the dataspace is contiguous. This is primarily used for reading the entire selection in one swoop. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE htri_t H5S__hyper_is_contiguous(const H5S_t *space) { hbool_t small_contiguous, /* Flag for small contiguous block */ large_contiguous; /* Flag for large contiguous block */ unsigned u; /* index variable */ htri_t ret_value = FALSE; /* Return value */ FUNC_ENTER_STATIC_NOERR HDassert(space); /* Check for a "regular" hyperslab selection */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { const H5S_hyper_dim_t *diminfo = space->select.sel_info.hslab->diminfo.opt; /* local alias for diminfo */ /* * For a regular hyperslab to be contiguous, it must have only one * block (i.e. count==1 in all dimensions) and the block size must be * the same as the dataspace extent's in all but the slowest changing * dimension. (dubbed "large contiguous" block) * * OR * * The selection must have only one block (i.e. count==1) in all * dimensions and the block size must be 1 in all but the fastest * changing dimension. (dubbed "small contiguous" block) */ /* Initialize flags */ large_contiguous = TRUE; /* assume true and reset if the dimensions don't match */ small_contiguous = FALSE; /* assume false initially */ /* Check for a "large contigous" block */ for (u = 0; u < space->extent.rank; u++) { if (diminfo[u].count > 1) { large_contiguous = FALSE; break; } /* end if */ if (u > 0 && diminfo[u].block != space->extent.size[u]) { large_contiguous = FALSE; break; } /* end if */ } /* end for */ /* If we didn't find a large contiguous block, check for a small one */ if (!large_contiguous) { small_contiguous = TRUE; for (u = 0; u < space->extent.rank; u++) { if (diminfo[u].count > 1) { small_contiguous = FALSE; break; } /* end if */ if (u < (space->extent.rank - 1) && diminfo[u].block != 1) { small_contiguous = FALSE; break; } /* end if */ } /* end for */ } /* end if */ /* Indicate true if it's either a large or small contiguous block */ if (large_contiguous || small_contiguous) ret_value = TRUE; } /* end if */ else { H5S_hyper_span_info_t *spans; /* Hyperslab span info node */ H5S_hyper_span_t * span; /* Hyperslab span node */ /* * For a hyperslab to be contiguous, it must have only one block and * either it's size must be the same as the dataspace extent's in all * but the slowest changing dimension * OR * block size must be 1 in all but the fastest changing dimension. */ /* Initialize flags */ large_contiguous = TRUE; /* assume true and reset if the dimensions don't match */ small_contiguous = FALSE; /* assume false initially */ /* Get information for slowest changing information */ spans = space->select.sel_info.hslab->span_lst; span = spans->head; /* If there are multiple spans in the slowest changing dimension, the selection isn't contiguous */ if (span->next != NULL) large_contiguous = FALSE; else { /* Now check the rest of the dimensions */ if (span->down != NULL) { u = 1; /* Current dimension working on */ /* Get the span information for the next fastest dimension */ spans = span->down; /* Cycle down the spans until we run out of down spans or find a non-contiguous span */ while (spans != NULL) { span = spans->head; /* Check that this is the only span and it spans the entire dimension */ if (span->next != NULL) { large_contiguous = FALSE; break; } /* end if */ else { /* If this span doesn't cover the entire dimension, then this selection isn't * contiguous */ if (((span->high - span->low) + 1) != space->extent.size[u]) { large_contiguous = FALSE; break; } /* end if */ else { /* Walk down to the next span */ spans = span->down; /* Increment dimension */ u++; } /* end else */ } /* end else */ } /* end while */ } /* end if */ } /* end else */ /* If we didn't find a large contiguous block, check for a small one */ if (!large_contiguous) { small_contiguous = TRUE; /* Get information for slowest changing information */ spans = space->select.sel_info.hslab->span_lst; span = spans->head; /* Current dimension working on */ u = 0; /* Cycle down the spans until we run out of down spans or find a non-contiguous span */ while (spans != NULL) { span = spans->head; /* Check that this is the only span and it spans the entire dimension */ if (span->next != NULL) { small_contiguous = FALSE; break; } /* end if */ else { /* If this span doesn't cover the entire dimension, then this selection isn't contiguous */ if (u < (space->extent.rank - 1) && ((span->high - span->low) + 1) != 1) { small_contiguous = FALSE; break; } /* end if */ else { /* Walk down to the next span */ spans = span->down; /* Increment dimension */ u++; } /* end else */ } /* end else */ } /* end while */ } /* end if */ /* Indicate true if it's either a large or small contiguous block */ if (large_contiguous || small_contiguous) ret_value = TRUE; } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_is_contiguous() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_is_single PURPOSE Check if a hyperslab selection is a single block within the dataspace extent. USAGE htri_t H5S__hyper_is_single(space) H5S_t *space; IN: Dataspace pointer to check RETURNS TRUE/FALSE/FAIL DESCRIPTION Checks to see if the current selection in the dataspace is a single block. This is primarily used for reading the entire selection in one swoop. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE htri_t H5S__hyper_is_single(const H5S_t *space) { htri_t ret_value = TRUE; /* return value */ FUNC_ENTER_STATIC_NOERR HDassert(space); /* Check for a "single" hyperslab selection */ /* (No need to rebuild the dimension info yet, since the span-tree * algorithm is fast -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { unsigned u; /* index variable */ /* * For a regular hyperslab to be single, it must have only one * block (i.e. count==1 in all dimensions) */ /* Check for a single block */ for (u = 0; u < space->extent.rank; u++) if (space->select.sel_info.hslab->diminfo.opt[u].count > 1) HGOTO_DONE(FALSE) } /* end if */ else { H5S_hyper_span_info_t *spans; /* Hyperslab span info node */ /* * For a region to be single, it must have only one block */ /* Get information for slowest changing information */ spans = space->select.sel_info.hslab->span_lst; /* Cycle down the spans until we run out of down spans or find a non-contiguous span */ while (spans != NULL) { H5S_hyper_span_t *span; /* Hyperslab span node */ span = spans->head; /* Check that this is the only span and it spans the entire dimension */ if (span->next != NULL) HGOTO_DONE(FALSE) else /* Walk down to the next span */ spans = span->down; } /* end while */ } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_is_single() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_is_regular PURPOSE Check if a hyperslab selection is "regular" USAGE htri_t H5S__hyper_is_regular(space) const H5S_t *space; IN: Dataspace pointer to check RETURNS TRUE/FALSE/FAIL DESCRIPTION Checks to see if the current selection in a dataspace is the a regular pattern. This is primarily used for reading the entire selection in one swoop. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static htri_t H5S__hyper_is_regular(const H5S_t *space) { htri_t ret_value = FAIL; /* return value */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(space); /* Attempt to rebuild diminfo if it is invalid and has not been confirmed * to be impossible. */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild((H5S_t *)space); /* Casting away const OK -NAF */ /* Only simple check for regular hyperslabs for now... */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) ret_value = TRUE; else ret_value = FALSE; FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_is_regular() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_spans_shape_same_helper PURPOSE Helper routine to check if two hyperslab span trees are the same shape USAGE hbool_t H5S__hyper_spans_shape_same_helper(span1, span2, offset, rest_zeros) H5S_hyper_span_info_t *span_info1; IN: First span tree to compare H5S_hyper_span_info_t *span_info2; IN: Second span tree to compare hssize_t offset[]; IN: Offset between the span trees hbool_t rest_zeros[]; IN: Array of flags which indicate the rest of the offset[] array is zero values. RETURNS TRUE (1) or FALSE (0) on success, can't fail DESCRIPTION Compare two hyperslab span trees to determine if they refer to a selection with the same shape, with a possible (constant) offset between their elements. Very similar to H5S__hyper_cmp_spans, except the selected elements can be offset by a vector. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE hbool_t H5S__hyper_spans_shape_same_helper(const H5S_hyper_span_info_t *span_info1, const H5S_hyper_span_info_t *span_info2, hssize_t offset[], hbool_t rest_zeros[]) { hbool_t ret_value = TRUE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(span_info1); HDassert(span_info2); HDassert(offset); HDassert(rest_zeros); /* Compare low & high bounds for this span list */ /* (Could compare lower dimensions also, but not certain if * that's worth it. - QAK, 2019/01/23) */ if ((hsize_t)((hssize_t)span_info1->low_bounds[0] + offset[0]) != span_info2->low_bounds[0]) HGOTO_DONE(FALSE) else if ((hsize_t)((hssize_t)span_info1->high_bounds[0] + offset[0]) != span_info2->high_bounds[0]) HGOTO_DONE(FALSE) else { const H5S_hyper_span_t *span1; const H5S_hyper_span_t *span2; /* Get the pointers to the actual lists of spans */ span1 = span_info1->head; span2 = span_info2->head; /* Sanity checking */ HDassert(span1); HDassert(span2); /* infinite loop which must be broken out of */ while (1) { /* Check for both spans being NULL */ if (span1 == NULL && span2 == NULL) HGOTO_DONE(TRUE) /* Check for one span being NULL */ if (span1 == NULL || span2 == NULL) HGOTO_DONE(FALSE) /* Check if the actual low & high span information is the same */ if ((hsize_t)((hssize_t)span1->low + offset[0]) != span2->low || (hsize_t)((hssize_t)span1->high + offset[0]) != span2->high) HGOTO_DONE(FALSE) /* Check for down tree for this span */ if (span1->down != NULL || span2->down != NULL) { /* If the rest of the span trees have a zero offset, use the faster comparison routine */ if (rest_zeros[0]) { if (!H5S__hyper_cmp_spans(span1->down, span2->down)) HGOTO_DONE(FALSE) else { /* Keep going... */ } /* end else */ } /* end if */ else { if (!H5S__hyper_spans_shape_same_helper(span1->down, span2->down, &offset[1], &rest_zeros[1])) HGOTO_DONE(FALSE) else { /* Keep going... */ } /* end else */ } /* end else */ } /* end if */ else { /* Keep going... */ } /* end else */ /* Advance to the next nodes in the span list */ span1 = span1->next; span2 = span2->next; } /* end while */ } /* end else */ /* Fall through, with default return value of 'TRUE' if spans were already visited */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_spans_shape_same_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_spans_shape_same PURPOSE Check if two hyperslab span trees are the same shape USAGE hbool_t H5S__hyper_spans_shape_same(span1, span2) H5S_hyper_span_info_t *span_info1; IN: First span tree to compare H5S_hyper_span_info_t *span_info2; IN: Second span tree to compare RETURNS TRUE (1) or FALSE (0) on success, can't fail DESCRIPTION Compare two hyperslab span trees to determine if they refer to a selection with the same shape. Very similar to H5S__hyper_cmp_spans, except the selected elements can be offset by a vector. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE hbool_t H5S__hyper_spans_shape_same(const H5S_hyper_span_info_t *span_info1, const H5S_hyper_span_info_t *span_info2, unsigned ndims) { const H5S_hyper_span_t *span1; /* Pointer to spans in first span tree */ const H5S_hyper_span_t *span2; /* Pointer to spans in second span tree */ hssize_t offset[H5S_MAX_RANK]; /* Offset vector for selections */ hbool_t rest_zeros[H5S_MAX_RANK]; /* Vector of flags to indicate when remaining offset is all zero */ hbool_t zero_offset; /* Whether the two selections have a non-zero offset */ unsigned u; /* Local index variable */ hbool_t ret_value = TRUE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(span_info1); HDassert(span_info2); HDassert(ndims > 0); /* Initialize arrays */ HDmemset(offset, 0, sizeof(offset)); HDmemset(rest_zeros, 0, sizeof(rest_zeros)); /* Check for an offset between the two selections */ span1 = span_info1->head; span2 = span_info2->head; zero_offset = TRUE; for (u = 0; u < ndims; u++) { /* Check for offset in this dimension */ if (span1->low != span2->low) { offset[u] = (hssize_t)span2->low - (hssize_t)span1->low; /* Indicate that the offset vector is not all zeros */ if (zero_offset) zero_offset = FALSE; } /* end if */ /* Sanity check */ /* (Both span trees must have the same depth) */ HDassert((span1->down && span2->down) || (NULL == span1->down && NULL == span2->down)); /* Advance to next dimension */ if (span1->down) { span1 = span1->down->head; span2 = span2->down->head; } /* end if */ } /* end for */ /* Check if there's a "tail" of all zeros in a non-zero offset vector */ if (!zero_offset) { int i; /* Local index variable */ /* Find first non-zero offset, from the fastest dimension up */ for (i = (int)(ndims - 1); i >= 0; i--) if (offset[i]) { rest_zeros[i] = TRUE; break; } /* end if */ /* Sanity check */ /* (Must eventually have found a non-zero offset) */ HDassert(i >= 0); } /* end if */ /* If the offset vector is all zero, we can use the faster span tree * comparison routine. Otherwise, use a generalized version of that * routine. */ if (zero_offset) ret_value = H5S__hyper_cmp_spans(span_info1, span_info2); else ret_value = H5S__hyper_spans_shape_same_helper(span_info1, span_info2, offset, rest_zeros); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_spans_shape_same() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_shape_same PURPOSE Check if a two hyperslab selections are the same shape USAGE htri_t H5S__hyper_shape_same(space1, space2) const H5S_t *space1; IN: First dataspace to check const H5S_t *space2; IN: Second dataspace to check RETURNS TRUE / FALSE / FAIL DESCRIPTION Checks to see if the current selection in each dataspace are the same shape. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Handles when both are regular in an efficient way, otherwise converts both to span tree form (if necessary) and compares efficiently them in that form. Rank of space1 must always be >= to rank of space2. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static htri_t H5S__hyper_shape_same(const H5S_t *space1, const H5S_t *space2) { unsigned space1_rank; /* Number of dimensions of first dataspace */ unsigned space2_rank; /* Number of dimensions of second dataspace */ htri_t ret_value = TRUE; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space1); HDassert(space2); /* Get dataspace ranks */ space1_rank = space1->extent.rank; space2_rank = space2->extent.rank; /* Sanity check */ HDassert(space1_rank >= space2_rank); HDassert(space2_rank > 0); /* Rebuild diminfo if it is invalid and has not been confirmed to be * impossible */ if (space1->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild((H5S_t *)space1); /* Casting away const OK -QAK */ if (space2->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild((H5S_t *)space2); /* Casting away const OK -QAK */ /* If both are regular hyperslabs, compare their diminfo values */ if (space1->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES && space2->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { int space1_dim; /* Current dimension in first dataspace */ int space2_dim; /* Current dimension in second dataspace */ /* Initialize dimensions */ space1_dim = (int)space1_rank - 1; space2_dim = (int)space2_rank - 1; /* Check that the shapes are the same in the common dimensions, and that * block == 1 in all dimensions that appear only in space1. */ while (space2_dim >= 0) { if (space1->select.sel_info.hslab->diminfo.opt[space1_dim].stride != space2->select.sel_info.hslab->diminfo.opt[space2_dim].stride) HGOTO_DONE(FALSE) if (space1->select.sel_info.hslab->diminfo.opt[space1_dim].count != space2->select.sel_info.hslab->diminfo.opt[space2_dim].count) HGOTO_DONE(FALSE) if (space1->select.sel_info.hslab->diminfo.opt[space1_dim].block != space2->select.sel_info.hslab->diminfo.opt[space2_dim].block) HGOTO_DONE(FALSE) space1_dim--; space2_dim--; } /* end while */ while (space1_dim >= 0) { if (space1->select.sel_info.hslab->diminfo.opt[space1_dim].block != 1) HGOTO_DONE(FALSE) space1_dim--; } /* end while */ } /* end if */ /* If both aren't regular, use fast irregular comparison */ else { H5S_hyper_span_info_t *spans1; /* Hyperslab spans for first dataspace */ /* Make certain that both selections have span trees */ if (NULL == space1->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans((H5S_t *)space1) < 0) /* Casting away const OK -QAK */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "can't construct span tree for hyperslab selection") if (NULL == space2->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans((H5S_t *)space2) < 0) /* Casting away const OK -QAK */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "can't construct span tree for hyperslab selection") /* If rank of space A is different (guaranteed greater) than * rank of space B, walk down the span tree, verifying * that the block size is 1 on the way down. */ if (space1_rank > space2_rank) { unsigned diff_rank = space1_rank - space2_rank; /* Difference in ranks */ /* Walk down the dimensions */ spans1 = space1->select.sel_info.hslab->span_lst; while (diff_rank > 0) { H5S_hyper_span_t *span; /* Span for this dimension */ /* Get pointer to first span in tree */ span = spans1->head; /* Check for more spans in this dimension */ if (span->next) HGOTO_DONE(FALSE) /* Check for span size > 1 element */ if (span->low != span->high) HGOTO_DONE(FALSE) /* Walk down to the next dimension */ spans1 = span->down; diff_rank--; } /* end while */ /* Sanity check */ HDassert(spans1); } /* end if */ else spans1 = space1->select.sel_info.hslab->span_lst; /* Compare the span trees */ ret_value = H5S__hyper_spans_shape_same(spans1, space2->select.sel_info.hslab->span_lst, space2_rank); } /* end else */ /* Fall through with 'TRUE' value, if not set earlier */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_shape_same() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_release PURPOSE Release hyperslab selection information for a dataspace USAGE herr_t H5S__hyper_release(space) H5S_t *space; IN: Pointer to dataspace RETURNS Non-negative on success/Negative on failure DESCRIPTION Releases all hyperslab selection information for a dataspace GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_release(H5S_t *space) { FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(space)); /* Reset the number of points selected */ space->select.num_elem = 0; /* Release irregular hyperslab information */ if (space->select.sel_info.hslab) { if (space->select.sel_info.hslab->span_lst != NULL) H5S__hyper_free_span_info(space->select.sel_info.hslab->span_lst); /* Release space for the hyperslab selection information */ space->select.sel_info.hslab = H5FL_FREE(H5S_hyper_sel_t, space->select.sel_info.hslab); } /* end if */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_release() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_coord_to_span PURPOSE Create a span tree for a single element USAGE H5S_hyper_span_t *H5S__hyper_coord_to_span(rank, coords) unsigned rank; IN: Number of dimensions of coordinate hsize_t *coords; IN: Location of element RETURNS Non-NULL pointer to new span tree on success, NULL on failure DESCRIPTION Create a span tree for a single element GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_t * H5S__hyper_coord_to_span(unsigned rank, const hsize_t *coords) { H5S_hyper_span_t * new_span; /* Pointer to new span tree for coordinate */ H5S_hyper_span_info_t *down = NULL; /* Pointer to new span tree for next level down */ H5S_hyper_span_t * ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC HDassert(rank > 0); HDassert(coords); /* Search for location to insert new element in tree */ if (rank > 1) { /* Allocate a span info node for coordinates below this one */ if (NULL == (down = H5S__hyper_new_span_info(rank - 1))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Set the low & high bounds for this span info node */ H5MM_memcpy(down->low_bounds, &coords[1], (rank - 1) * sizeof(hsize_t)); H5MM_memcpy(down->high_bounds, &coords[1], (rank - 1) * sizeof(hsize_t)); /* Build span tree for coordinates below this one */ if (NULL == (down->head = H5S__hyper_coord_to_span(rank - 1, &coords[1]))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Update the tail pointer of the down dimension, and it's a single span element */ down->tail = down->head; } /* end if */ /* Build span for this coordinate */ if (NULL == (new_span = H5S__hyper_new_span(coords[0], coords[0], down, NULL))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Set return value */ ret_value = new_span; done: if (ret_value == NULL && down != NULL) H5S__hyper_free_span_info(down); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_coord_to_span() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_add_span_element_helper PURPOSE Helper routine to add a single element to a span tree USAGE herr_t H5S__hyper_add_span_element_helper(span_tree, rank, coords, first_dim_modified) H5S_hyper_span_info_t *span_tree; IN/OUT: Pointer to span tree to append to unsigned rank; IN: Number of dimensions of coordinates hsize_t *coords; IN: Location of element to add to span tree int *first_dim_modified; IN: Index of the first dimension modified RETURNS Non-negative on success, negative on failure DESCRIPTION Add a single element to an existing span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Assumes that the element is not already covered by the span tree EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_add_span_element_helper(H5S_hyper_span_info_t *span_tree, unsigned rank, const hsize_t *coords, int *first_dim_modified) { H5S_hyper_span_t *tail_span; /* Pointer to the tail span of one dimension */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(span_tree); HDassert(rank > 0); HDassert(coords); HDassert(first_dim_modified); /* Get pointer to last span in span tree */ tail_span = span_tree->tail; /* Determine if tail span includes a portion of the coordinate */ /* (Should never happen with the lowest level in the span tree) */ if (coords[0] >= tail_span->low && coords[0] <= tail_span->high) { H5S_hyper_span_t *prev_down_tail_span; /* Pointer to previous down spans' tail pointer */ hsize_t prev_down_tail_span_high; /* Value of previous down spans' tail's high value */ /* Retain into about down spans' tail */ prev_down_tail_span = tail_span->down->tail; prev_down_tail_span_high = tail_span->down->tail->high; /* Drop down a dimension */ HDassert(rank > 1); if (H5S__hyper_add_span_element_helper(tail_span->down, rank - 1, &coords[1], first_dim_modified) < 0) HGOTO_ERROR(H5E_DATASET, H5E_CANTINSERT, FAIL, "can't insert coordinate into span tree") /* Check & update high bounds for lower dimensions */ if (*first_dim_modified >= 0) { unsigned first_dim; /* First dimension modified, relative to this span tree */ hbool_t first_dim_set = FALSE; /* Whether first dimension modified is set */ unsigned u; /* Local index variable */ /* Adjust first dimension modified to be relative to this span tree */ first_dim = (unsigned)(*first_dim_modified + 1); /* Reset modified dimension, in case no bounds in this span tree change */ *first_dim_modified = -1; /* Iterate through coordinates */ for (u = first_dim; u < rank; u++) { /* Check if coordinate is outside the bounds for this span tree */ if (coords[u] > span_tree->high_bounds[u]) { /* Update high bounds for this tree */ span_tree->high_bounds[u] = coords[u]; /* Need to signal to higher dimensions if high bounds changed */ if (!first_dim_set) { *first_dim_modified = (int)u; first_dim_set = TRUE; } /* end if */ } /* end if */ } /* end for */ } /* end if */ /* Check if previous tail span in down spans is different than current * tail span, or if its high value changed, in which case we should * check if the updated node can share down spans with other nodes. */ if (tail_span->down->tail != prev_down_tail_span || prev_down_tail_span_high != tail_span->down->tail->high) { H5S_hyper_span_t *stop_span; /* Pointer to span to stop at */ H5S_hyper_span_t *tmp_span; /* Temporary pointer to a span */ uint64_t op_gen; /* Operation generation value */ /* Determine which span to stop at */ if (tail_span->down->tail != prev_down_tail_span) { /* Sanity check */ HDassert(prev_down_tail_span->next == tail_span->down->tail); /* Set the span to stop at */ stop_span = prev_down_tail_span; } /* end if */ else { /* Sanity check */ HDassert(prev_down_tail_span_high != tail_span->down->tail->high); /* Set the span to stop at */ stop_span = tail_span->down->tail; } /* end else */ /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Check if the 'stop' span in the "down tree" is equal to any other * spans in the list of spans in the span tree. * * If so, release last span information and make last span merge into * previous span (if possible), or at least share their "down tree" * information. */ tmp_span = tail_span->down->head; while (tmp_span != stop_span) { hbool_t attempt_merge_spans = FALSE; /* Whether to merge spans */ /* Different tests for when to run the 'merge' algorithm, * depending whether there's "down trees" or not. */ if (NULL == tmp_span->down) { /* Spin through spans until we find the one before the 'stop' span */ if (tmp_span->next == stop_span) attempt_merge_spans = TRUE; } /* end if */ else { /* Check if we've compared the 'stop' span's "down tree" to * this span's "down tree" already. */ if (tmp_span->down->op_info[0].op_gen != op_gen) { if (H5S__hyper_cmp_spans(tmp_span->down, stop_span->down)) attempt_merge_spans = TRUE; /* Remember that we visited this span's "down tree" already */ /* (Because it wasn't the same as the 'stop' span's down tree * and we don't need to compare it again) */ tmp_span->down->op_info[0].op_gen = op_gen; } /* end if */ } /* end else */ /* Check for merging into previous span */ if (attempt_merge_spans) { if (tmp_span->high + 1 == stop_span->low) { /* Increase size of previous span */ tmp_span->high++; /* Update pointers appropriately */ if (stop_span == prev_down_tail_span) { /* Sanity check */ HDassert(stop_span->next == tail_span->down->tail); tmp_span->next = stop_span->next; } /* end if */ else { /* Sanity check */ HDassert(tmp_span->next == tail_span->down->tail); tmp_span->next = NULL; tail_span->down->tail = tmp_span; } /* end else */ /* Release last span created */ H5S__hyper_free_span(stop_span); } /* end if */ /* Span is disjoint, but has the same "down tree" selection */ /* (If it has a "down tree") */ else if (stop_span->down) { /* Release "down tree" information */ H5S__hyper_free_span_info(stop_span->down); /* Point at earlier span's "down tree" */ stop_span->down = tmp_span->down; /* Increment reference count on shared "down tree" */ stop_span->down->count++; } /* end else */ /* Found span to merge into, break out now */ break; } /* end if */ /* Advance to next span to check */ tmp_span = tmp_span->next; } /* end while */ } /* end if */ } /* end if */ else { unsigned u; /* Local index variable */ /* Check if we made it all the way to the bottom span list in the tree * and the new coordinate adjoins the current tail span. */ if (rank == 1 && (tail_span->high + 1) == coords[0]) /* Append element to current tail span */ tail_span->high++; else { H5S_hyper_span_t *new_span; /* New span created for element */ /* Make span tree for current coordinate(s) */ if (NULL == (new_span = H5S__hyper_coord_to_span(rank, coords))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab spans for coordinate") /* Add new span to span tree list */ tail_span->next = new_span; span_tree->tail = new_span; } /* end else */ /* Update high bound for current span tree */ HDassert(coords[0] > span_tree->high_bounds[0]); span_tree->high_bounds[0] = coords[0]; /* Update high bounds for dimensions below this one */ for (u = 1; u < rank; u++) if (coords[u] > span_tree->high_bounds[u]) span_tree->high_bounds[u] = coords[u]; /* Need to signal to higher dimensions that high bounds changed */ *first_dim_modified = 0; } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_add_span_element_helper() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_add_span_element PURPOSE Add a single element to a span tree USAGE herr_t H5S_hyper_add_span_element(space, span_tree, rank, coords) H5S_t *space; IN/OUT: Pointer to dataspace to add coordinate to unsigned rank; IN: Number of dimensions of coordinates hsize_t *coords; IN: Location of element to add to span tree RETURNS Non-negative on success, negative on failure DESCRIPTION Add a single element to an existing span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Assumes that the element is not already in the dataspace's selection NOTE: There's also an assumption about the context of this function call - This function is only called is only being called from H5D_chunk_mem_cb in src/H5Dchunk.c, when the library is iterating over a memory selection, so the coordinates passed to H5S_hyper_add_span_element will always be in increasing order (according to a row-major (i.e. C, not FORTRAN) scan) over the dataset. Therefore, for every input of coordinates, only the last span element (i.e., the tail pointer) in one dimension is checked against the input. NOTE: This algorithm is definitely "correct" and tries to conserve memory as much as possible, but it's doing a _lot_ of work that might be better spent running a similar algorithm to "condense" the span tree (possibly even back into a regular selection) just before the selection is used for I/O on the chunk. I'm not going to spend the time on this currently, but it does sound like a good direction to explore. QAK, 2019/01/24 EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5S_hyper_add_span_element(H5S_t *space, unsigned rank, const hsize_t *coords) { H5S_hyper_span_info_t *head = NULL; /* Pointer to new head of span tree */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI(FAIL) HDassert(space); HDassert(rank > 0); HDassert(coords); HDassert(space->extent.rank == rank); /* Check if this is the first element in the selection */ if (NULL == space->select.sel_info.hslab) { /* Allocate a span info node */ if (NULL == (head = H5S__hyper_new_span_info(rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span info") /* Set the low & high bounds for this span info node */ H5MM_memcpy(head->low_bounds, coords, rank * sizeof(hsize_t)); H5MM_memcpy(head->high_bounds, coords, rank * sizeof(hsize_t)); /* Set the reference count */ head->count = 1; /* Build span tree for this coordinate */ if (NULL == (head->head = H5S__hyper_coord_to_span(rank, coords))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab spans for coordinate") /* Update the tail pointer of this newly created span in dimension "rank" */ head->tail = head->head; /* Allocate selection info */ if (NULL == (space->select.sel_info.hslab = H5FL_MALLOC(H5S_hyper_sel_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab selection") /* Set the selection to the new span tree */ space->select.sel_info.hslab->span_lst = head; /* Set selection type */ space->select.type = H5S_sel_hyper; /* Reset "regular" hyperslab flag */ space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; /* Set unlim_dim */ space->select.sel_info.hslab->unlim_dim = -1; /* Set # of elements in selection */ space->select.num_elem = 1; } /* end if */ else { int first_dim_modified = -1; /* Index of first dimension modified */ /* Add the element to the current set of spans */ if (H5S__hyper_add_span_element_helper(space->select.sel_info.hslab->span_lst, rank, coords, &first_dim_modified) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't insert coordinate into span tree") /* Increment # of elements in selection */ space->select.num_elem++; } /* end else */ done: if (ret_value < 0) if (head) H5S__hyper_free_span_info(head); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_add_span_element() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_intersect_block_helper PURPOSE Helper routine to detect intersections in span trees USAGE hbool_t H5S__hyper_intersect_block_helper(spans, rank, start, end, op_info_i, op_gen) H5S_hyper_span_info_t *spans; IN: First span tree to operate with unsigned rank; IN: Number of dimensions for span tree hsize_t *start; IN: Starting coordinate for block hsize_t *end; IN: Ending coordinate for block unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURN Non-negative (TRUE/FALSE) on success, can't fail DESCRIPTION Quickly detect intersections between span tree and block GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hbool_t H5S__hyper_intersect_block_helper(H5S_hyper_span_info_t *spans, unsigned rank, const hsize_t *start, const hsize_t *end, unsigned op_info_i, uint64_t op_gen) { hbool_t ret_value = FALSE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(spans); HDassert(start); HDassert(end); /* Check if we've already visited this span tree */ if (spans->op_info[op_info_i].op_gen != op_gen) { H5S_hyper_span_t *curr; /* Pointer to current span in 1st span tree */ unsigned u; /* Local index variable */ /* Verify that there is a possibility of an overlap by checking the block * against the low & high bounds for the span tree. */ for (u = 0; u < rank; u++) if (start[u] > spans->high_bounds[u] || end[u] < spans->low_bounds[u]) HGOTO_DONE(FALSE) /* Get the span list for spans in this tree */ curr = spans->head; /* Iterate over the spans in the tree */ while (curr != NULL) { /* Check for span entirely before block */ if (curr->high < *start) /* Advance to next span in this dimension */ curr = curr->next; /* If this span is past the end of the block, then we're done in this dimension */ else if (curr->low > *end) HGOTO_DONE(FALSE) /* block & span overlap */ else { /* If this is the bottom dimension, then the span tree overlaps the block */ if (curr->down == NULL) HGOTO_DONE(TRUE) /* Recursively check spans in next dimension down */ else { /* If there is an intersection in the "down" dimensions, * the span trees overlap. */ if (H5S__hyper_intersect_block_helper(curr->down, rank - 1, start + 1, end + 1, op_info_i, op_gen)) HGOTO_DONE(TRUE) /* No intersection in down dimensions, advance to next span */ curr = curr->next; } /* end else */ } /* end else */ } /* end while */ /* Set the tree's operation generation */ spans->op_info[op_info_i].op_gen = op_gen; } /* end if */ /* Fall through with 'FALSE' return value */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_intersect_block_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_intersect_block PURPOSE Detect intersections of selection with block USAGE htri_t H5S__hyper_intersect_block(space, start, end) const H5S_t *space; IN: Dataspace with selection to use const hsize_t *start; IN: Starting coordinate for block const hsize_t *end; IN: Ending coordinate for block RETURNS Non-negative TRUE / FALSE on success, negative on failure DESCRIPTION Quickly detect intersections between both regular hyperslabs and span trees with a block GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Does not use selection offset. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static htri_t H5S__hyper_intersect_block(const H5S_t *space, const hsize_t *start, const hsize_t *end) { htri_t ret_value = FAIL; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(space); HDassert(H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(space)); HDassert(start); HDassert(end); /* Attempt to rebuild diminfo if it is invalid and has not been confirmed * to be impossible. */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_NO) H5S__hyper_rebuild((H5S_t *)space); /* Casting away const OK -QAK */ /* Check for regular hyperslab intersection */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { hbool_t single_block; /* Whether the regular selection is a single block */ unsigned u; /* Local index variable */ /* Check for a single block */ /* For a regular hyperslab to be single, it must have only one block * (i.e. count == 1 in all dimensions). */ single_block = TRUE; for (u = 0; u < space->extent.rank; u++) if (space->select.sel_info.hslab->diminfo.opt[u].count > 1) single_block = FALSE; /* Single blocks have already been "compared" above, in the low / high * bound checking, so just return TRUE if we've reached here - they * would have been rejected earlier, if they didn't intersect. */ if (single_block) HGOTO_DONE(TRUE) else { /* Loop over the dimensions, checking for an intersection */ for (u = 0; u < space->extent.rank; u++) { /* If the block's start is <= the hyperslab start, they intersect */ /* (So, if the start is > the hyperslab start, check more conditions) */ if (start[u] > space->select.sel_info.hslab->diminfo.opt[u].start) { hsize_t adj_start; /* Start coord, adjusted for hyperslab selection parameters */ hsize_t nstride; /* Number of strides into the selection */ /* Adjust start coord for selection's 'start' offset */ adj_start = start[u] - space->select.sel_info.hslab->diminfo.opt[u].start; /* Compute # of strides into the selection */ if (space->select.sel_info.hslab->diminfo.opt[u].count > 1) nstride = adj_start / space->select.sel_info.hslab->diminfo.opt[u].stride; else nstride = 0; /* Sanity check */ HDassert(nstride <= space->select.sel_info.hslab->diminfo.opt[u].count); /* "Rebase" the adjusted start coord into the same range * range of values as the selections's first block. */ adj_start -= nstride * space->select.sel_info.hslab->diminfo.opt[u].stride; /* If the adjusted start doesn't fall within the first hyperslab * span, check for the block overlapping with the next one. */ if (adj_start >= space->select.sel_info.hslab->diminfo.opt[u].block) { hsize_t adj_end; /* End coord, adjusted for hyperslab selection parameters */ /* Adjust end coord for selection's 'start' offset */ adj_end = end[u] - space->select.sel_info.hslab->diminfo.opt[u].start; /* "Rebase" the adjusted end coord into the same range * range of values as the selections's first block. */ adj_end -= nstride * space->select.sel_info.hslab->diminfo.opt[u].stride; /* If block doesn't extend over beginning of next span, * it doesn't intersect. */ if (adj_end < space->select.sel_info.hslab->diminfo.opt[u].stride) HGOTO_DONE(FALSE) } /* end if */ } /* end if */ } /* end for */ /* If we've looped through all dimensions and none of them didn't * overlap, then all of them do, so we report TRUE. */ HGOTO_DONE(TRUE) } /* end else */ } /* end if */ else { uint64_t op_gen; /* Operation generation value */ /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Perform the span-by-span intersection check */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ ret_value = H5S__hyper_intersect_block_helper(space->select.sel_info.hslab->span_lst, space->extent.rank, start, end, 0, op_gen); } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_intersect_block() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_adjust_u_helper PURPOSE Helper routine to adjust offsets in span trees USAGE void H5S__hyper_adjust_u_helper(spans, rank, offset, op_info_i, op_gen) H5S_hyper_span_info_t *spans; IN: Span tree to operate with unsigned rank; IN: Number of dimensions for span tree const hsize_t *offset; IN: Offset to subtract unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURNS None DESCRIPTION Adjust the location of the spans in a span tree by subtracting an offset GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_adjust_u_helper(H5S_hyper_span_info_t *spans, unsigned rank, const hsize_t *offset, unsigned op_info_i, uint64_t op_gen) { FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(spans); HDassert(offset); /* Check if we've already set this span tree */ if (spans->op_info[op_info_i].op_gen != op_gen) { H5S_hyper_span_t *span; /* Pointer to current span in span tree */ unsigned u; /* Local index variable */ /* Adjust the span tree's low & high bounds */ for (u = 0; u < rank; u++) { HDassert(spans->low_bounds[u] >= offset[u]); spans->low_bounds[u] -= offset[u]; spans->high_bounds[u] -= offset[u]; } /* end for */ /* Iterate over the spans in tree */ span = spans->head; while (span != NULL) { /* Adjust span offset */ HDassert(span->low >= *offset); span->low -= *offset; span->high -= *offset; /* Recursively adjust spans in next dimension down */ if (span->down != NULL) H5S__hyper_adjust_u_helper(span->down, rank - 1, offset + 1, op_info_i, op_gen); /* Advance to next span in this dimension */ span = span->next; } /* end while */ /* Set the tree's operation generation */ spans->op_info[op_info_i].op_gen = op_gen; } /* end if */ FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_adjust_u_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_adjust_u PURPOSE Adjust a hyperslab selection by subtracting an offset USAGE void H5S__hyper_adjust_u(space,offset) H5S_t *space; IN/OUT: Pointer to dataspace to adjust const hsize_t *offset; IN: Offset to subtract RETURNS Non-negative on success, negative on failure DESCRIPTION Moves a hyperslab selection by subtracting an offset from it. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_adjust_u(H5S_t *space, const hsize_t *offset) { hbool_t non_zero_offset = FALSE; /* Whether any offset is non-zero */ unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(space); HDassert(offset); /* Check for an all-zero offset vector */ for (u = 0; u < space->extent.rank; u++) if (0 != offset[u]) { non_zero_offset = TRUE; break; } /* Only perform operation if the offset is non-zero */ if (non_zero_offset) { /* Subtract the offset from the "regular" coordinates, if they exist */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { for (u = 0; u < space->extent.rank; u++) { HDassert(space->select.sel_info.hslab->diminfo.opt[u].start >= offset[u]); space->select.sel_info.hslab->diminfo.opt[u].start -= offset[u]; /* Adjust the low & high bounds */ HDassert(space->select.sel_info.hslab->diminfo.low_bounds[u] >= offset[u]); space->select.sel_info.hslab->diminfo.low_bounds[u] -= offset[u]; space->select.sel_info.hslab->diminfo.high_bounds[u] -= offset[u]; } /* end for */ } /* end if */ /* Subtract the offset from the span tree coordinates, if they exist */ if (space->select.sel_info.hslab->span_lst) { uint64_t op_gen; /* Operation generation value */ /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Perform adjustment */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ H5S__hyper_adjust_u_helper(space->select.sel_info.hslab->span_lst, space->extent.rank, offset, 0, op_gen); } /* end if */ } /* end if */ FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_adjust_u() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_project_scalar * * Purpose: Projects a single element hyperslab selection into a scalar * dataspace * * Return: Non-negative on success, negative on failure. * * Programmer: Quincey Koziol * Sunday, July 18, 2010 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_project_scalar(const H5S_t *space, hsize_t *offset) { hsize_t block[H5S_MAX_RANK]; /* Block selected in base dataspace */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(space)); HDassert(offset); /* Check for a "regular" hyperslab selection */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { const H5S_hyper_dim_t *diminfo = space->select.sel_info.hslab->diminfo.opt; /* Alias for dataspace's diminfo information */ unsigned u; /* Counter */ /* Build the table of the initial offset */ for (u = 0; u < space->extent.rank; u++) { /* Sanity check diminfo */ HDassert(1 == diminfo[u].count); HDassert(1 == diminfo[u].block); /* Sanity check bounds, while we're here */ HDassert(diminfo[u].start == space->select.sel_info.hslab->diminfo.low_bounds[u]); /* Keep the offset for later */ block[u] = diminfo[u].start; } /* end for */ } /* end if */ else { const H5S_hyper_span_t *curr; /* Pointer to current hyperslab span */ unsigned curr_dim; /* Current dimension being operated on */ /* Advance down selected spans */ curr = space->select.sel_info.hslab->span_lst->head; curr_dim = 0; while (1) { /* Sanity checks */ HDassert(NULL == curr->next); HDassert(curr->low == curr->high); HDassert(curr_dim < space->extent.rank); /* Save the location of the selection in current dimension */ block[curr_dim] = curr->low; /* Advance down to next dimension */ if (curr->down) { curr = curr->down->head; curr_dim++; } /* end if */ else break; } /* end while */ } /* end else */ /* Calculate offset of selection in projected buffer */ *offset = H5VM_array_offset(space->extent.rank, space->extent.size, block); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_project_scalar() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_project_simple_lower * * Purpose: Projects a hyperslab selection onto/into a simple dataspace * of a lower rank * * Return: Non-negative on success, negative on failure. * * Programmer: Quincey Koziol * Sunday, July 18, 2010 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_project_simple_lower(const H5S_t *base_space, H5S_t *new_space) { H5S_hyper_span_info_t *down; /* Pointer to list of spans */ unsigned curr_dim; /* Current dimension being operated on */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(base_space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(base_space)); HDassert(new_space); HDassert(new_space->extent.rank < base_space->extent.rank); /* Walk down the span tree until we reach the selection to project */ down = base_space->select.sel_info.hslab->span_lst; curr_dim = 0; while (down && curr_dim < (base_space->extent.rank - new_space->extent.rank)) { /* Sanity check */ HDassert(NULL == down->head->next); /* Advance down to next dimension */ down = down->head->down; curr_dim++; } /* end while */ HDassert(down); /* Share the underlying hyperslab span information */ new_space->select.sel_info.hslab->span_lst = down; new_space->select.sel_info.hslab->span_lst->count++; FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_project_simple_lower() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_project_simple_higher * * Purpose: Projects a hyperslab selection onto/into a simple dataspace * of a higher rank * * Return: Non-negative on success, negative on failure. * * Programmer: Quincey Koziol * Sunday, July 18, 2010 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_project_simple_higher(const H5S_t *base_space, H5S_t *new_space) { H5S_hyper_span_t *prev_span = NULL; /* Pointer to previous list of spans */ unsigned delta_rank; /* Difference in dataspace ranks */ unsigned curr_dim; /* Current dimension being operated on */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(base_space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(base_space)); HDassert(new_space); HDassert(new_space->extent.rank > base_space->extent.rank); /* Create nodes until reaching the correct # of dimensions */ new_space->select.sel_info.hslab->span_lst = NULL; curr_dim = 0; delta_rank = (new_space->extent.rank - base_space->extent.rank); while (curr_dim < delta_rank) { H5S_hyper_span_info_t *new_span_info; /* Pointer to list of spans */ H5S_hyper_span_t * new_span; /* Temporary hyperslab span */ /* Allocate a new span_info node */ if (NULL == (new_span_info = H5S__hyper_new_span_info(new_space->extent.rank))) { if (prev_span) H5S__hyper_free_span(prev_span); HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span info") } /* end if */ /* Check for linking into higher span */ if (prev_span) prev_span->down = new_span_info; /* Allocate a new node */ if (NULL == (new_span = H5S__hyper_new_span((hsize_t)0, (hsize_t)0, NULL, NULL))) { HDassert(new_span_info); if (!prev_span) (void)H5FL_ARR_FREE(hbounds_t, new_span_info); HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") } /* end if */ /* Set the span_info information */ new_span_info->count = 1; new_span_info->head = new_span; new_span_info->tail = new_span; /* Set the bounding box */ for (u = 0; u < delta_rank; u++) { new_span_info->low_bounds[u] = 0; new_span_info->high_bounds[u] = 0; } /* end for */ for (; u < new_space->extent.rank; u++) { new_span_info->low_bounds[u] = base_space->select.sel_info.hslab->span_lst->low_bounds[u - delta_rank]; new_span_info->high_bounds[u] = base_space->select.sel_info.hslab->span_lst->high_bounds[u - delta_rank]; } /* end for */ /* Attach to new space, if top span info */ if (NULL == new_space->select.sel_info.hslab->span_lst) new_space->select.sel_info.hslab->span_lst = new_span_info; /* Remember previous span info */ prev_span = new_span; /* Advance to next dimension */ curr_dim++; } /* end while */ HDassert(new_space->select.sel_info.hslab->span_lst); HDassert(prev_span); /* Share the underlying hyperslab span information */ prev_span->down = base_space->select.sel_info.hslab->span_lst; prev_span->down->count++; done: if (ret_value < 0 && new_space->select.sel_info.hslab->span_lst) { if (new_space->select.sel_info.hslab->span_lst->head) H5S__hyper_free_span(new_space->select.sel_info.hslab->span_lst->head); new_space->select.sel_info.hslab->span_lst = (H5S_hyper_span_info_t *)H5FL_ARR_FREE(hbounds_t, new_space->select.sel_info.hslab->span_lst); } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_project_simple_higher() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_project_simple * * Purpose: Projects a hyperslab selection onto/into a simple dataspace * of a different rank * * Return: Non-negative on success, negative on failure. * * Programmer: Quincey Koziol * Sunday, July 18, 2010 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_project_simple(const H5S_t *base_space, H5S_t *new_space, hsize_t *offset) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(base_space && H5S_SEL_HYPERSLABS == H5S_GET_SELECT_TYPE(base_space)); HDassert(new_space); HDassert(offset); /* We are setting a new selection, remove any current selection in new dataspace */ if (H5S_SELECT_RELEASE(new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't release selection") /* Allocate space for the hyperslab selection information */ if (NULL == (new_space->select.sel_info.hslab = H5FL_MALLOC(H5S_hyper_sel_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab info") /* Set unlim_dim */ new_space->select.sel_info.hslab->unlim_dim = -1; /* Check for a "regular" hyperslab selection */ /* (No need to rebuild the dimension info yet -QAK) */ if (base_space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { unsigned base_space_dim; /* Current dimension in the base dataspace */ unsigned new_space_dim; /* Current dimension in the new dataspace */ unsigned u; /* Local index variable */ /* Check if the new space's rank is < or > base space's rank */ if (new_space->extent.rank < base_space->extent.rank) { const H5S_hyper_dim_t *opt_diminfo = base_space->select.sel_info.hslab->diminfo .opt; /* Alias for dataspace's diminfo information */ hsize_t block[H5S_MAX_RANK]; /* Block selected in base dataspace */ /* Compute the offset for the down-projection */ HDmemset(block, 0, sizeof(block)); for (u = 0; u < (base_space->extent.rank - new_space->extent.rank); u++) block[u] = opt_diminfo[u].start; *offset = H5VM_array_offset(base_space->extent.rank, base_space->extent.size, block); /* Set the correct dimensions for the base & new spaces */ base_space_dim = base_space->extent.rank - new_space->extent.rank; new_space_dim = 0; } /* end if */ else { HDassert(new_space->extent.rank > base_space->extent.rank); /* The offset is zero when projected into higher dimensions */ *offset = 0; /* Set the diminfo information for the higher dimensions */ for (new_space_dim = 0; new_space_dim < (new_space->extent.rank - base_space->extent.rank); new_space_dim++) { new_space->select.sel_info.hslab->diminfo.app[new_space_dim].start = 0; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].stride = 1; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].count = 1; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].block = 1; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].start = 0; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].stride = 1; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].count = 1; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].block = 1; } /* end for */ /* Start at beginning of base space's dimension info */ base_space_dim = 0; } /* end else */ /* Copy the diminfo */ while (base_space_dim < base_space->extent.rank) { new_space->select.sel_info.hslab->diminfo.app[new_space_dim].start = base_space->select.sel_info.hslab->diminfo.app[base_space_dim].start; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].stride = base_space->select.sel_info.hslab->diminfo.app[base_space_dim].stride; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].count = base_space->select.sel_info.hslab->diminfo.app[base_space_dim].count; new_space->select.sel_info.hslab->diminfo.app[new_space_dim].block = base_space->select.sel_info.hslab->diminfo.app[base_space_dim].block; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].start = base_space->select.sel_info.hslab->diminfo.opt[base_space_dim].start; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].stride = base_space->select.sel_info.hslab->diminfo.opt[base_space_dim].stride; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].count = base_space->select.sel_info.hslab->diminfo.opt[base_space_dim].count; new_space->select.sel_info.hslab->diminfo.opt[new_space_dim].block = base_space->select.sel_info.hslab->diminfo.opt[base_space_dim].block; /* Advance to next dimensions */ base_space_dim++; new_space_dim++; } /* end for */ /* Update the bounding box */ for (u = 0; u < new_space->extent.rank; u++) { new_space->select.sel_info.hslab->diminfo.low_bounds[u] = new_space->select.sel_info.hslab->diminfo.opt[u].start; new_space->select.sel_info.hslab->diminfo.high_bounds[u] = new_space->select.sel_info.hslab->diminfo.low_bounds[u] + new_space->select.sel_info.hslab->diminfo.opt[u].stride * (new_space->select.sel_info.hslab->diminfo.opt[u].count - 1) + (new_space->select.sel_info.hslab->diminfo.opt[u].block - 1); } /* end for */ /* Indicate that the dimension information is valid */ new_space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_YES; /* Indicate that there's no slab information */ new_space->select.sel_info.hslab->span_lst = NULL; } /* end if */ else { /* Check if the new space's rank is < or > base space's rank */ if (new_space->extent.rank < base_space->extent.rank) { const H5S_hyper_span_t *curr; /* Pointer to current hyperslab span */ hsize_t block[H5S_MAX_RANK]; /* Block selected in base dataspace */ unsigned curr_dim; /* Current dimension being operated on */ /* Clear the block buffer */ HDmemset(block, 0, sizeof(block)); /* Advance down selected spans */ curr = base_space->select.sel_info.hslab->span_lst->head; curr_dim = 0; while (curr && curr_dim < (base_space->extent.rank - new_space->extent.rank)) { /* Save the location of the selection in current dimension */ block[curr_dim] = curr->low; /* Advance down to next dimension */ curr = curr->down->head; curr_dim++; } /* end while */ /* Compute the offset for the down-projection */ *offset = H5VM_array_offset(base_space->extent.rank, base_space->extent.size, block); /* Project the base space's selection down in less dimensions */ if (H5S__hyper_project_simple_lower(base_space, new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't project hyperslab selection into less dimensions") } /* end if */ else { HDassert(new_space->extent.rank > base_space->extent.rank); /* The offset is zero when projected into higher dimensions */ *offset = 0; /* Project the base space's selection down in more dimensions */ if (H5S__hyper_project_simple_higher(base_space, new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't project hyperslab selection into less dimensions") } /* end else */ /* Copy the status of the dimension information */ new_space->select.sel_info.hslab->diminfo_valid = base_space->select.sel_info.hslab->diminfo_valid; } /* end else */ /* Number of elements selected will be the same */ new_space->select.num_elem = base_space->select.num_elem; /* Set selection type */ new_space->select.type = H5S_sel_hyper; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_project_simple() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_adjust_s_helper PURPOSE Helper routine to adjust offsets in span trees USAGE void H5S__hyper_adjust_s_helper(spans, rank, offset, op_info_i, op_gen) H5S_hyper_span_info_t *spans; IN: Span tree to operate with unsigned rank; IN: Number of dimensions for span tree const hssize_t *offset; IN: Offset to subtract unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURNS None DESCRIPTION Adjust the location of the spans in a span tree by subtracting an offset GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_adjust_s_helper(H5S_hyper_span_info_t *spans, unsigned rank, const hssize_t *offset, unsigned op_info_i, uint64_t op_gen) { FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(spans); HDassert(offset); /* Check if we've already set this span tree */ if (spans->op_info[op_info_i].op_gen != op_gen) { H5S_hyper_span_t *span; /* Pointer to current span in span tree */ unsigned u; /* Local index variable */ /* Adjust the span tree's low & high bounds */ for (u = 0; u < rank; u++) { HDassert((hssize_t)spans->low_bounds[u] >= offset[u]); spans->low_bounds[u] = (hsize_t)((hssize_t)spans->low_bounds[u] - offset[u]); spans->high_bounds[u] = (hsize_t)((hssize_t)spans->high_bounds[u] - offset[u]); } /* end for */ /* Iterate over the spans in tree */ span = spans->head; while (span != NULL) { /* Adjust span offset */ HDassert((hssize_t)span->low >= *offset); span->low = (hsize_t)((hssize_t)span->low - *offset); span->high = (hsize_t)((hssize_t)span->high - *offset); /* Recursively adjust spans in next dimension down */ if (span->down != NULL) H5S__hyper_adjust_s_helper(span->down, rank - 1, offset + 1, op_info_i, op_gen); /* Advance to next span in this dimension */ span = span->next; } /* end while */ /* Set the tree's operation generation */ spans->op_info[op_info_i].op_gen = op_gen; } /* end if */ FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_adjust_s_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_adjust_s PURPOSE Adjust a hyperslab selection by subtracting an offset USAGE herr_t H5S__hyper_adjust_s(space,offset) H5S_t *space; IN/OUT: Pointer to dataspace to adjust const hssize_t *offset; IN: Offset to subtract RETURNS Non-negative on success, negative on failure DESCRIPTION Moves a hyperslab selection by subtracting an offset from it. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_adjust_s(H5S_t *space, const hssize_t *offset) { hbool_t non_zero_offset = FALSE; /* Whether any offset is non-zero */ unsigned u; /* Local index variable */ FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(space); HDassert(offset); /* Check for an all-zero offset vector */ for (u = 0; u < space->extent.rank; u++) if (0 != offset[u]) { non_zero_offset = TRUE; break; } /* end if */ /* Only perform operation if the offset is non-zero */ if (non_zero_offset) { /* Subtract the offset from the "regular" coordinates, if they exist */ /* (No need to rebuild the dimension info yet -QAK) */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { for (u = 0; u < space->extent.rank; u++) { HDassert((hssize_t)space->select.sel_info.hslab->diminfo.opt[u].start >= offset[u]); space->select.sel_info.hslab->diminfo.opt[u].start = (hsize_t)((hssize_t)space->select.sel_info.hslab->diminfo.opt[u].start - offset[u]); /* Adjust the low & high bounds */ HDassert((hssize_t)space->select.sel_info.hslab->diminfo.low_bounds[u] >= offset[u]); space->select.sel_info.hslab->diminfo.low_bounds[u] = (hsize_t)((hssize_t)space->select.sel_info.hslab->diminfo.low_bounds[u] - offset[u]); space->select.sel_info.hslab->diminfo.high_bounds[u] = (hsize_t)((hssize_t)space->select.sel_info.hslab->diminfo.high_bounds[u] - offset[u]); } /* end for */ } /* end if */ /* Subtract the offset from the span tree coordinates, if they exist */ if (space->select.sel_info.hslab->span_lst) { uint64_t op_gen; /* Operation generation value */ /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Perform the adjustment */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ H5S__hyper_adjust_s_helper(space->select.sel_info.hslab->span_lst, space->extent.rank, offset, 0, op_gen); } /* end if */ } FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5S__hyper_adjust_s() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_normalize_offset PURPOSE "Normalize" a hyperslab selection by adjusting it's coordinates by the amount of the selection offset. USAGE htri_t H5S_hyper_normalize_offset(space, old_offset) H5S_t *space; IN/OUT: Pointer to dataspace to move hssize_t *old_offset; OUT: Pointer to space to store old offset RETURNS TRUE/FALSE for hyperslab selection, FAIL on error DESCRIPTION Copies the current selection offset into the array provided, then inverts the selection offset, subtracts the offset from the hyperslab selection and resets the offset to zero. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ htri_t H5S_hyper_normalize_offset(H5S_t *space, hssize_t *old_offset) { htri_t ret_value = FALSE; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Sanity checks */ HDassert(space); HDassert(old_offset); /* Check for hyperslab selection & offset changed */ if (H5S_GET_SELECT_TYPE(space) == H5S_SEL_HYPERSLABS && space->select.offset_changed) { unsigned u; /* Local index variable */ /* Copy & invert the selection offset */ for (u = 0; u < space->extent.rank; u++) { old_offset[u] = space->select.offset[u]; space->select.offset[u] = -space->select.offset[u]; } /* end for */ /* Call the 'adjust' routine */ if (H5S__hyper_adjust_s(space, space->select.offset) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't adjust selection") /* Zero out the selection offset */ HDmemset(space->select.offset, 0, sizeof(hssize_t) * space->extent.rank); /* Indicate that the offset was normalized */ ret_value = TRUE; } /* end if */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_normalize_offset() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_denormalize_offset PURPOSE "Denormalize" a hyperslab selection by reverse adjusting it's coordinates by the amount of the former selection offset. USAGE herr_t H5S_hyper_denormalize_offset(space, old_offset) H5S_t *space; IN/OUT: Pointer to dataspace to move hssize_t *old_offset; IN: Pointer to old offset array RETURNS Non-negative on success, negative on failure DESCRIPTION Subtracts the old offset from the current selection (canceling out the effect of the "normalize" routine), then restores the old offset into the dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5S_hyper_denormalize_offset(H5S_t *space, const hssize_t *old_offset) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Sanity checks */ HDassert(space); HDassert(H5S_GET_SELECT_TYPE(space) == H5S_SEL_HYPERSLABS); /* Call the 'adjust' routine */ if (H5S__hyper_adjust_s(space, old_offset) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't adjust selection") /* Copy the selection offset over */ H5MM_memcpy(space->select.offset, old_offset, sizeof(hssize_t) * space->extent.rank); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_denormalize_offset() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_append_span PURPOSE Create a new span and append to span list USAGE herr_t H5S__hyper_append_span(span_tree, ndims, low, high, down) H5S_hyper_span_info_t **span_tree; IN/OUT: Pointer to span tree to append to unsigned ndims; IN: Number of dimension for span hsize_t low, high; IN: Low and high bounds for new span node H5S_hyper_span_info_t *down; IN: Down span tree for new node RETURNS Non-negative on success, negative on failure DESCRIPTION Create a new span node and append to a span list. Update the previous span in the list also. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_append_span(H5S_hyper_span_info_t **span_tree, unsigned ndims, hsize_t low, hsize_t high, H5S_hyper_span_info_t *down) { H5S_hyper_span_t *new_span = NULL; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity checks */ HDassert(span_tree); /* Check for adding first node to merged spans */ if (*span_tree == NULL) { /* Allocate new span node to append to list */ if (NULL == (new_span = H5S__hyper_new_span(low, high, down, NULL))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") /* Make new span the first node in span list */ /* Allocate a new span_info node */ if (NULL == (*span_tree = H5S__hyper_new_span_info(ndims))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") /* Set the span tree's basic information */ (*span_tree)->count = 1; (*span_tree)->head = new_span; (*span_tree)->tail = new_span; /* Set low & high bounds for new span tree */ (*span_tree)->low_bounds[0] = low; (*span_tree)->high_bounds[0] = high; if (down) { /* Sanity check */ HDassert(ndims > 1); H5MM_memcpy(&((*span_tree)->low_bounds[1]), down->low_bounds, sizeof(hsize_t) * (ndims - 1)); H5MM_memcpy(&((*span_tree)->high_bounds[1]), down->high_bounds, sizeof(hsize_t) * (ndims - 1)); } /* end if */ } /* end if */ /* Merge or append to existing merged spans list */ else { htri_t down_cmp = (-1); /* Comparison value for down spans */ /* Check if span can just extend the previous merged span */ if ((((*span_tree)->tail->high + 1) == low) && (down_cmp = H5S__hyper_cmp_spans(down, (*span_tree)->tail->down))) { /* Extend previous merged span to include new high bound */ (*span_tree)->tail->high = high; /* Extend span tree's high bound in this dimension */ /* (No need to update lower dimensions, since this span shares them with previous span) */ (*span_tree)->high_bounds[0] = high; } /* end if */ else { H5S_hyper_span_info_t *new_down; /* Down pointer for new span node */ /* Sanity check */ /* (If down_cmp was set to TRUE above, we won't be in this branch) */ HDassert(down_cmp != TRUE); /* Check if there is actually a down span */ if (down) { /* Check if the down spans for the new span node are the same as the previous span node */ /* (Uses the 'down span comparison' from earlier, if already computed) */ if (down_cmp < 0 && (down_cmp = H5S__hyper_cmp_spans(down, (*span_tree)->tail->down))) /* Share the previous span's down span tree */ new_down = (*span_tree)->tail->down; else new_down = down; } /* end if */ else new_down = NULL; /* Allocate new span node to append to list */ if (NULL == (new_span = H5S__hyper_new_span(low, high, new_down, NULL))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") /* Update the high bounds for current dimension */ (*span_tree)->high_bounds[0] = high; /* Update low & high bounds in lower dimensions, if there are any */ if (down) { /* Sanity checks */ HDassert(ndims > 1); HDassert(down_cmp >= 0); /* Check if we are sharing down spans with a previous node */ /* (Only need to check for bounds changing if down spans aren't shared) */ if (down_cmp == FALSE) { unsigned u; /* Local index variable */ /* Loop over lower dimensions, checking & updating low & high bounds */ for (u = 0; u < (ndims - 1); u++) { if (down->low_bounds[u] < (*span_tree)->low_bounds[u + 1]) (*span_tree)->low_bounds[u + 1] = down->low_bounds[u]; if (down->high_bounds[u] > (*span_tree)->high_bounds[u + 1]) (*span_tree)->high_bounds[u + 1] = down->high_bounds[u]; } /* end for */ } /* end if */ } /* end if */ /* Append to end of merged spans list */ (*span_tree)->tail->next = new_span; (*span_tree)->tail = new_span; } /* end else */ } /* end else */ done: if (ret_value < 0) if (new_span) H5S__hyper_free_span(new_span); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_append_span() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_clip_spans PURPOSE Clip a new span tree against the current spans in the hyperslab selection USAGE herr_t H5S__hyper_clip_spans(span_a, span_b, selector, curr_dim, dim_size, span_a_b_bounds[4], all_clips_bound, a_not_b, a_and_b, b_not_a) H5S_hyper_span_t *a_spans; IN: Span tree 'a' to clip with. H5S_hyper_span_t *b_spans; IN: Span tree 'b' to clip with. unsigned selector; IN: The parameter deciding which output is needed (only considering the last three bits ABC: If A is set, then a_not_b is needed; If B is set, then a_and_b is needed; If C is set, then b_not_a is needed; ) unsigned ndims; IN: Number of dimensions of this span tree H5S_hyper_span_t **a_not_b; OUT: Span tree of 'a' hyperslab spans which doesn't overlap with 'b' hyperslab spans. H5S_hyper_span_t **a_and_b; OUT: Span tree of 'a' hyperslab spans which overlaps with 'b' hyperslab spans. H5S_hyper_span_t **b_not_a; OUT: Span tree of 'b' hyperslab spans which doesn't overlap with 'a' hyperslab spans. RETURNS non-negative on success, negative on failure DESCRIPTION Clip one span tree ('a') against another span tree ('b'). Creates span trees for the area defined by the 'a' span tree which does not overlap the 'b' span tree ("a not b"), the area defined by the overlap of the 'a' hyperslab span tree and the 'b' span tree ("a and b"), and the area defined by the 'b' hyperslab span tree which does not overlap the 'a' span tree ("b not a"). GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_clip_spans(H5S_hyper_span_info_t *a_spans, H5S_hyper_span_info_t *b_spans, unsigned selector, unsigned ndims, H5S_hyper_span_info_t **a_not_b, H5S_hyper_span_info_t **a_and_b, H5S_hyper_span_info_t **b_not_a) { hbool_t need_a_not_b; /* Whether to generate a_not_b list */ hbool_t need_a_and_b; /* Whether to generate a_and_b list */ hbool_t need_b_not_a; /* Whether to generate b_not_a list */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(a_spans); HDassert(b_spans); HDassert(a_not_b); HDassert(a_and_b); HDassert(b_not_a); /* Set which list(s) to be generated, based on selector */ need_a_not_b = ((selector & H5S_HYPER_COMPUTE_A_NOT_B) != 0); need_a_and_b = ((selector & H5S_HYPER_COMPUTE_A_AND_B) != 0); need_b_not_a = ((selector & H5S_HYPER_COMPUTE_B_NOT_A) != 0); /* Check if both span trees are not defined */ if (a_spans == NULL && b_spans == NULL) { *a_not_b = NULL; *a_and_b = NULL; *b_not_a = NULL; } /* end if */ /* If span 'a' is not defined, but 'b' is, copy 'b' and set the other return span trees to empty */ else if (a_spans == NULL) { *a_not_b = NULL; *a_and_b = NULL; if (need_b_not_a) { if (NULL == (*b_not_a = H5S__hyper_copy_span(b_spans, ndims))) HGOTO_ERROR(H5E_INTERNAL, H5E_CANTCOPY, FAIL, "can't copy hyperslab span tree") } /* end if */ else *b_not_a = NULL; } /* end if */ /* If span 'b' is not defined, but 'a' is, copy 'a' and set the other return span trees to empty */ else if (b_spans == NULL) { *a_and_b = NULL; *b_not_a = NULL; if (need_a_not_b) { if (NULL == (*a_not_b = H5S__hyper_copy_span(a_spans, ndims))) HGOTO_ERROR(H5E_INTERNAL, H5E_CANTCOPY, FAIL, "can't copy hyperslab span tree") } /* end if */ else *a_not_b = NULL; } /* end if */ /* If span 'a' and 'b' are both defined, calculate the proper span trees */ else { /* Check if both span trees completely overlap */ if (H5S__hyper_cmp_spans(a_spans, b_spans)) { *a_not_b = NULL; *b_not_a = NULL; if (need_a_and_b) { if (NULL == (*a_and_b = H5S__hyper_copy_span(a_spans, ndims))) HGOTO_ERROR(H5E_INTERNAL, H5E_CANTCOPY, FAIL, "can't copy hyperslab span tree") } /* end if */ else *a_and_b = NULL; } /* end if */ else { H5S_hyper_span_t *span_a; /* Pointer to a node in span tree 'a' */ H5S_hyper_span_t *span_b; /* Pointer to a node in span tree 'b' */ hbool_t recover_a, recover_b; /* Flags to indicate when to recover temporary spans */ /* Get the pointers to the new and old span lists */ span_a = a_spans->head; span_b = b_spans->head; /* No spans to recover yet */ recover_a = recover_b = FALSE; /* Work through the list of spans in the new list */ while (span_a != NULL && span_b != NULL) { H5S_hyper_span_info_t *down_a_not_b; /* Temporary pointer to a_not_b span tree of down spans for overlapping nodes */ H5S_hyper_span_info_t *down_a_and_b; /* Temporary pointer to a_and_b span tree of down spans for overlapping nodes */ H5S_hyper_span_info_t *down_b_not_a; /* Temporary pointer to b_and_a span tree of down spans for overlapping nodes */ H5S_hyper_span_t *tmp_span; /* Temporary pointer to new span */ /* Check if span 'a' is completely before span 'b' */ /* AAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ if (span_a->high < span_b->low) { /* Copy span 'a' and add to a_not_b list */ /* Merge/add span 'a' with/to a_not_b list */ if (need_a_not_b) if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Advance span 'a', leave span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); } /* end if */ /* Check if span 'a' overlaps only the lower bound */ /* of span 'b' , up to the upper bound of span 'b' */ /* AAAAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low < span_b->low && (span_a->high >= span_b->low && span_a->high <= span_b->high)) { /* Split span 'a' into two parts at the low bound of span 'b' */ /* Merge/add lower part of span 'a' with/to a_not_b list */ if (need_a_not_b) if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_b->low - 1, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Check for overlaps between upper part of span 'a' and lower part of span 'b' */ /* Make certain both spans either have a down span or both don't have one */ HDassert((span_a->down != NULL && span_b->down != NULL) || (span_a->down == NULL && span_b->down == NULL)); /* If there are no down spans, just add the overlapping area to the a_and_b list */ if (span_a->down == NULL) { /* Merge/add overlapped part with/to a_and_b list */ if (need_a_and_b) if (H5S__hyper_append_span(a_and_b, ndims, span_b->low, span_a->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ /* If there are down spans, check for the overlap in them and add to each appropriate list */ else { /* NULL out the temporary pointers to clipped areas in down spans */ down_a_not_b = NULL; down_a_and_b = NULL; down_b_not_a = NULL; /* Check for overlaps in the 'down spans' of span 'a' & 'b' */ /** Note: since the bound box of remaining dimensions * has been updated in the following clip function (via * all_clips_bounds), there's no need updating the bound box * after each append call in the following codes */ if (H5S__hyper_clip_spans(span_a->down, span_b->down, selector, ndims - 1, &down_a_not_b, &down_a_and_b, &down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't clip hyperslab information") /* Check for additions to the a_not_b list */ if (down_a_not_b) { HDassert(need_a_not_b == TRUE); /* Merge/add overlapped part with/to a_not_b list */ if (H5S__hyper_append_span(a_not_b, ndims, span_b->low, span_a->high, down_a_not_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_not_b); } /* end if */ /* Check for additions to the a_and_b list */ if (down_a_and_b) { HDassert(need_a_and_b == TRUE); /* Merge/add overlapped part with/to a_and_b list */ if (H5S__hyper_append_span(a_and_b, ndims, span_b->low, span_a->high, down_a_and_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_and_b); } /* end if */ /* Check for additions to the b_not_a list */ if (down_b_not_a) { HDassert(need_b_not_a == TRUE); /* Merge/add overlapped part with/to b_not_a list */ if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_a->high, down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_b_not_a); } /* end if */ } /* end else */ /* Split off upper part of span 'b' at upper span of span 'a' */ /* Check if there is actually an upper part of span 'b' to split off */ if (span_a->high < span_b->high) { /* Allocate new span node for upper part of span 'b' */ if (NULL == (tmp_span = H5S__hyper_new_span(span_a->high + 1, span_b->high, span_b->down, span_b->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_NOSPACE, FAIL, "can't allocate hyperslab span") /* Advance span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); /* Make upper part of span 'b' into new span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, tmp_span); recover_b = TRUE; } /* end if */ /* No upper part of span 'b' to split */ else { /* Advance both 'a' and 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end if */ /* Check if span 'a' overlaps the lower & upper bound */ /* of span 'b' */ /* AAAAAAAAAAAAAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low < span_b->low && span_a->high > span_b->high) { /* Split off lower part of span 'a' at lower span of span 'b' */ /* Merge/add lower part of span 'a' with/to a_not_b list */ if (need_a_not_b) if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_b->low - 1, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Check for overlaps between middle part of span 'a' and span 'b' */ /* Make certain both spans either have a down span or both don't have one */ HDassert((span_a->down != NULL && span_b->down != NULL) || (span_a->down == NULL && span_b->down == NULL)); /* If there are no down spans, just add the overlapping area to the a_and_b list */ if (span_a->down == NULL) { /* Merge/add overlapped part with/to a_and_b list */ if (need_a_and_b) if (H5S__hyper_append_span(a_and_b, ndims, span_b->low, span_b->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ /* If there are down spans, check for the overlap in them and add to each appropriate list */ else { /* NULL out the temporary pointers to clipped areas in down spans */ down_a_not_b = NULL; down_a_and_b = NULL; down_b_not_a = NULL; /* Check for overlaps in the 'down spans' of span 'a' & 'b' */ if (H5S__hyper_clip_spans(span_a->down, span_b->down, selector, ndims - 1, &down_a_not_b, &down_a_and_b, &down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't clip hyperslab information") /* Check for additions to the a_not_b list */ if (down_a_not_b) { HDassert(need_a_not_b == TRUE); /* Merge/add overlapped part with/to a_not_b list */ if (H5S__hyper_append_span(a_not_b, ndims, span_b->low, span_b->high, down_a_not_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_not_b); } /* end if */ /* Check for additions to the a_and_b list */ if (down_a_and_b) { HDassert(need_a_and_b == TRUE); /* Merge/add overlapped part with/to a_and_b list */ if (H5S__hyper_append_span(a_and_b, ndims, span_b->low, span_b->high, down_a_and_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_and_b); } /* end if */ /* Check for additions to the b_not_a list */ if (down_b_not_a) { HDassert(need_b_not_a == TRUE); /* Merge/add overlapped part with/to b_not_a list */ if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_b->high, down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_b_not_a); } /* end if */ } /* end else */ /* Split off upper part of span 'a' at upper span of span 'b' */ /* Allocate new span node for upper part of span 'a' */ if (NULL == (tmp_span = H5S__hyper_new_span(span_b->high + 1, span_a->high, span_a->down, span_a->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_NOSPACE, FAIL, "can't allocate hyperslab span") /* Make upper part of span 'a' the new span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, tmp_span); recover_a = TRUE; /* Advance span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end if */ /* Check if span 'a' is entirely within span 'b' */ /* AAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low >= span_b->low && span_a->high <= span_b->high) { /* Split off lower part of span 'b' at lower span of span 'a' */ /* Check if there is actually a lower part of span 'b' to split off */ if (span_a->low > span_b->low) { /* Merge/add lower part of span 'b' with/to b_not_a list */ if (need_b_not_a) if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_a->low - 1, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* Keep going, nothing to split off */ } /* end else */ /* Check for overlaps between span 'a' and midle of span 'b' */ /* Make certain both spans either have a down span or both don't have one */ HDassert((span_a->down != NULL && span_b->down != NULL) || (span_a->down == NULL && span_b->down == NULL)); /* If there are no down spans, just add the overlapping area to the a_and_b list */ if (span_a->down == NULL) { /* Merge/add overlapped part with/to a_and_b list */ if (need_a_and_b) if (H5S__hyper_append_span(a_and_b, ndims, span_a->low, span_a->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ /* If there are down spans, check for the overlap in them and add to each appropriate list */ else { /* NULL out the temporary pointers to clipped areas in down spans */ down_a_not_b = NULL; down_a_and_b = NULL; down_b_not_a = NULL; /* Check for overlaps in the 'down spans' of span 'a' & 'b' */ if (H5S__hyper_clip_spans(span_a->down, span_b->down, selector, ndims - 1, &down_a_not_b, &down_a_and_b, &down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't clip hyperslab information") /* Check for additions to the a_not_b list */ if (down_a_not_b) { HDassert(need_a_not_b == TRUE); /* Merge/add overlapped part with/to a_not_b list */ if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_a->high, down_a_not_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_not_b); } /* end if */ /* Check for additions to the a_and_b list */ if (down_a_and_b) { HDassert(need_a_and_b == TRUE); /* Merge/add overlapped part with/to a_and_b list */ if (H5S__hyper_append_span(a_and_b, ndims, span_a->low, span_a->high, down_a_and_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_and_b); } /* end if */ /* Check for additions to the b_not_a list */ if (down_b_not_a) { HDassert(need_b_not_a == TRUE); /* Merge/add overlapped part with/to b_not_a list */ if (H5S__hyper_append_span(b_not_a, ndims, span_a->low, span_a->high, down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_b_not_a); } /* end if */ } /* end else */ /* Check if there is actually an upper part of span 'b' to split off */ if (span_a->high < span_b->high) { /* Split off upper part of span 'b' at upper span of span 'a' */ /* Allocate new span node for upper part of spans 'a' */ if (NULL == (tmp_span = H5S__hyper_new_span(span_a->high + 1, span_b->high, span_b->down, span_b->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") /* And advance span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); /* Make upper part of span 'b' the new span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, tmp_span); recover_b = TRUE; } /* end if */ else { /* Advance both span 'a' & span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end if */ /* Check if span 'a' overlaps only the upper bound */ /* of span 'b' */ /* AAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if ((span_a->low >= span_b->low && span_a->low <= span_b->high) && span_a->high > span_b->high) { /* Check if there is actually a lower part of span 'b' to split off */ if (span_a->low > span_b->low) { /* Split off lower part of span 'b' at lower span of span 'a' */ /* Merge/add lower part of span 'b' with/to b_not_a list */ if (need_b_not_a) if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_a->low - 1, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* Keep going, nothing to split off */ } /* end else */ /* Check for overlaps between lower part of span 'a' and upper part of span 'b' */ /* Make certain both spans either have a down span or both don't have one */ HDassert((span_a->down != NULL && span_b->down != NULL) || (span_a->down == NULL && span_b->down == NULL)); /* If there are no down spans, just add the overlapping area to the a_and_b list */ if (span_a->down == NULL) { /* Merge/add overlapped part with/to a_and_b list */ if (need_a_and_b) if (H5S__hyper_append_span(a_and_b, ndims, span_a->low, span_b->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ /* If there are down spans, check for the overlap in them and add to each appropriate list */ else { /* NULL out the temporary pointers to clipped areas in down spans */ down_a_not_b = NULL; down_a_and_b = NULL; down_b_not_a = NULL; /* Check for overlaps in the 'down spans' of span 'a' & 'b' */ if (H5S__hyper_clip_spans(span_a->down, span_b->down, selector, ndims - 1, &down_a_not_b, &down_a_and_b, &down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't clip hyperslab information") /* Check for additions to the a_not_b list */ if (down_a_not_b) { HDassert(need_a_not_b == TRUE); /* Merge/add overlapped part with/to a_not_b list */ if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_b->high, down_a_not_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_not_b); } /* end if */ /* Check for additions to the a_and_b list */ if (down_a_and_b) { HDassert(need_a_and_b == TRUE); /* Merge/add overlapped part with/to a_and_b list */ if (H5S__hyper_append_span(a_and_b, ndims, span_a->low, span_b->high, down_a_and_b) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_a_and_b); } /* end if */ /* Check for additions to the b_not_a list */ if (down_b_not_a) { HDassert(need_b_not_a == TRUE); /* Merge/add overlapped part with/to b_not_a list */ if (H5S__hyper_append_span(b_not_a, ndims, span_a->low, span_b->high, down_b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Release the down span tree generated */ H5S__hyper_free_span_info(down_b_not_a); } /* end if */ } /* end else */ /* Split off upper part of span 'a' at upper span of span 'b' */ /* Allocate new span node for upper part of span 'a' */ if (NULL == (tmp_span = H5S__hyper_new_span(span_b->high + 1, span_a->high, span_a->down, span_a->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab span") /* Make upper part of span 'a' into new span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, tmp_span); recover_a = TRUE; /* Advance span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end if */ /* span 'a' must be entirely above span 'b' */ /* AAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else { /* Copy span 'b' and add to b_not_a list */ /* Merge/add span 'b' with/to b_not_a list */ if (need_b_not_a) if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_b->high, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Advance span 'b', leave span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end while */ /* Clean up 'a' spans which haven't been covered yet */ if (span_a != NULL && span_b == NULL) { /* Check if need to merge/add 'a' spans with/to a_not_b list */ if (need_a_not_b) { /* (This loop, and the similar one below for 'b' spans, * could be replaced with an optimized routine that quickly * appended the remaining spans to the 'not' list, but * until it looks like it's taking a lot of time for an * important use case, it's been left generic, and similar * to other code above. -QAK, 2019/02/01) */ while (span_a != NULL) { /* Copy span 'a' and add to a_not_b list */ if (H5S__hyper_append_span(a_not_b, ndims, span_a->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Advance to the next 'a' span */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); } /* end while */ } /* end if */ else { /* Free the span, if it's generated */ if (recover_a) H5S__hyper_free_span(span_a); } /* end else */ } /* end if */ /* Clean up 'b' spans which haven't been covered yet */ else if (span_a == NULL && span_b != NULL) { /* Check if need to merge/add 'b' spans with/to b_not_a list */ if (need_b_not_a) { /* (This loop, and the similar one above for 'a' spans, * could be replaced with an optimized routine that quickly * appended the remaining spans to the 'not' list, but * until it looks like it's taking a lot of time for an * important use case, it's been left generic, and similar * to other code above. -QAK, 2019/02/01) */ while (span_b != NULL) { /* Copy span 'b' and add to b_not_a list */ if (H5S__hyper_append_span(b_not_a, ndims, span_b->low, span_b->high, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") /* Advance to the next 'b' span */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end while */ } /* end if */ else { /* Free the span, if it's generated */ if (recover_b) H5S__hyper_free_span(span_b); } /* end else */ } /* end if */ else /* Sanity check */ HDassert(span_a == NULL && span_b == NULL); } /* end else */ } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_clip_spans() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_merge_spans_helper PURPOSE Merge two hyperslab span tree together USAGE H5S_hyper_span_info_t *H5S__hyper_merge_spans_helper(a_spans, b_spans) H5S_hyper_span_info_t *a_spans; IN: First hyperslab spans to merge together H5S_hyper_span_info_t *b_spans; IN: Second hyperslab spans to merge together unsigned ndims; IN: Number of dimensions of this span tree RETURNS Pointer to span tree containing the merged spans on success, NULL on failure DESCRIPTION Merge two sets of hyperslab spans together and return the span tree from the merged set. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Handles merging span trees that overlap. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_info_t * H5S__hyper_merge_spans_helper(H5S_hyper_span_info_t *a_spans, H5S_hyper_span_info_t *b_spans, unsigned ndims) { H5S_hyper_span_info_t *merged_spans = NULL; /* Pointer to the merged span tree */ H5S_hyper_span_info_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Make certain both 'a' & 'b' spans have down span trees or neither does */ HDassert((a_spans != NULL && b_spans != NULL) || (a_spans == NULL && b_spans == NULL)); /* Check if the span trees for the 'a' span and the 'b' span are the same */ if (H5S__hyper_cmp_spans(a_spans, b_spans)) { if (a_spans == NULL) merged_spans = NULL; else { /* Copy one of the span trees to return */ if (NULL == (merged_spans = H5S__hyper_copy_span(a_spans, ndims))) HGOTO_ERROR(H5E_INTERNAL, H5E_CANTCOPY, NULL, "can't copy hyperslab span tree") } /* end else */ } /* end if */ else { H5S_hyper_span_t *span_a; /* Pointer to current span 'a' working on */ H5S_hyper_span_t *span_b; /* Pointer to current span 'b' working on */ hbool_t recover_a, recover_b; /* Flags to indicate when to recover temporary spans */ /* Get the pointers to the 'a' and 'b' span lists */ span_a = a_spans->head; span_b = b_spans->head; /* No spans to recover yet */ recover_a = recover_b = FALSE; /* Work through the list of spans in the new list */ while (span_a != NULL && span_b != NULL) { H5S_hyper_span_info_t *tmp_spans; /* Pointer to temporary new span tree */ H5S_hyper_span_t * tmp_span; /* Pointer to temporary new span */ /* Check if the 'a' span is completely before 'b' span */ /* AAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ if (span_a->high < span_b->low) { /* Merge/add span 'a' with/to the merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Advance span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); } /* end if */ /* Check if span 'a' overlaps only the lower bound */ /* of span 'b', up to the upper bound of span 'b' */ /* AAAAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low < span_b->low && (span_a->high >= span_b->low && span_a->high <= span_b->high)) { /* Check if span 'a' and span 'b' down spans are equal */ if (H5S__hyper_cmp_spans(span_a->down, span_b->down)) { /* Merge/add copy of span 'a' with/to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* Merge/add lower part of span 'a' with/to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_b->low - 1, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Get merged span tree for overlapped section */ tmp_spans = H5S__hyper_merge_spans_helper(span_a->down, span_b->down, ndims - 1); /* Merge/add overlapped section to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_a->high, tmp_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Release merged span tree for overlapped section */ H5S__hyper_free_span_info(tmp_spans); } /* end else */ /* Check if there is an upper part of span 'b' */ if (span_a->high < span_b->high) { /* Copy upper part of span 'b' as new span 'b' */ /* Allocate new span node to append to list */ if (NULL == (tmp_span = H5S__hyper_new_span(span_a->high + 1, span_b->high, span_b->down, span_b->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Advance span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); /* Set new span 'b' to tmp_span */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, tmp_span); recover_b = TRUE; } /* end if */ else { /* Advance both span 'a' & 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end if */ /* Check if span 'a' overlaps the lower & upper bound */ /* of span 'b' */ /* AAAAAAAAAAAAAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low < span_b->low && span_a->high > span_b->high) { /* Check if span 'a' and span 'b' down spans are equal */ if (H5S__hyper_cmp_spans(span_a->down, span_b->down)) { /* Merge/add copy of lower & middle parts of span 'a' to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_b->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* Merge/add lower part of span 'a' to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_b->low - 1, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Get merged span tree for overlapped section */ tmp_spans = H5S__hyper_merge_spans_helper(span_a->down, span_b->down, ndims - 1); /* Merge/add overlapped section to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_b->high, tmp_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Release merged span tree for overlapped section */ H5S__hyper_free_span_info(tmp_spans); } /* end else */ /* Copy upper part of span 'a' as new span 'a' (remember to free) */ /* Allocate new span node to append to list */ if (NULL == (tmp_span = H5S__hyper_new_span(span_b->high + 1, span_a->high, span_a->down, span_a->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Set new span 'a' to tmp_span */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, tmp_span); recover_a = TRUE; /* Advance span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end if */ /* Check if span 'a' is entirely within span 'b' */ /* AAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if (span_a->low >= span_b->low && span_a->high <= span_b->high) { /* Check if span 'a' and span 'b' down spans are equal */ if (H5S__hyper_cmp_spans(span_a->down, span_b->down)) { /* Merge/add copy of lower & middle parts of span 'b' to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* Check if there is a lower part of span 'b' */ if (span_a->low > span_b->low) { /* Merge/add lower part of span 'b' to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_a->low - 1, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* No lower part of span 'b' , keep going... */ } /* end else */ /* Get merged span tree for overlapped section */ tmp_spans = H5S__hyper_merge_spans_helper(span_a->down, span_b->down, ndims - 1); /* Merge/add overlapped section to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_a->high, tmp_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Release merged span tree for overlapped section */ H5S__hyper_free_span_info(tmp_spans); } /* end else */ /* Check if there is an upper part of span 'b' */ if (span_a->high < span_b->high) { /* Copy upper part of span 'b' as new span 'b' (remember to free) */ /* Allocate new span node to append to list */ if (NULL == (tmp_span = H5S__hyper_new_span(span_a->high + 1, span_b->high, span_b->down, span_b->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Advance span 'a' */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); /* Set new span 'b' to tmp_span */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, tmp_span); recover_b = TRUE; } /* end if */ else { /* Advance both spans */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end if */ /* Check if span 'a' overlaps only the upper bound */ /* of span 'b' */ /* AAAAAAAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else if ((span_a->low >= span_b->low && span_a->low <= span_b->high) && span_a->high > span_b->high) { /* Check if span 'a' and span 'b' down spans are equal */ if (H5S__hyper_cmp_spans(span_a->down, span_b->down)) { /* Merge/add copy of span 'b' to merged spans if so */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_b->high, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* Check if there is a lower part of span 'b' */ if (span_a->low > span_b->low) { /* Merge/add lower part of span 'b' to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_a->low - 1, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") } /* end if */ else { /* No lower part of span 'b' , keep going... */ } /* end else */ /* Get merged span tree for overlapped section */ tmp_spans = H5S__hyper_merge_spans_helper(span_a->down, span_b->down, ndims - 1); /* Merge/add overlapped section to merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_b->high, tmp_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Release merged span tree for overlapped section */ H5S__hyper_free_span_info(tmp_spans); } /* end else */ /* Copy upper part of span 'a' as new span 'a' */ /* Allocate new span node to append to list */ if (NULL == (tmp_span = H5S__hyper_new_span(span_b->high + 1, span_a->high, span_a->down, span_a->next))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Set new span 'a' to tmp_span */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, tmp_span); recover_a = TRUE; /* Advance span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end if */ /* Span 'a' must be entirely above span 'b' */ /* AAAAA */ /* <-----------------------------------> */ /* BBBBBBBBBB */ else { /* Merge/add span 'b' with the merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_b->high, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Advance span 'b' */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end else */ } /* end while */ /* Clean up 'a' spans which haven't been added to the list of merged spans */ if (span_a != NULL && span_b == NULL) { while (span_a != NULL) { /* Merge/add all 'a' spans into the merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_a->low, span_a->high, span_a->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Advance to next 'a' span, until all processed */ H5S_HYPER_ADVANCE_SPAN(recover_a, span_a, span_a->next); } /* end while */ } /* end if */ /* Clean up 'b' spans which haven't been added to the list of merged spans */ if (span_a == NULL && span_b != NULL) { while (span_b != NULL) { /* Merge/add all 'b' spans into the merged spans */ if (H5S__hyper_append_span(&merged_spans, ndims, span_b->low, span_b->high, span_b->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, NULL, "can't allocate hyperslab span") /* Advance to next 'b' span, until all processed */ H5S_HYPER_ADVANCE_SPAN(recover_b, span_b, span_b->next); } /* end while */ } /* end if */ } /* end else */ /* Set return value */ ret_value = merged_spans; done: if (ret_value == NULL) if (merged_spans) H5S__hyper_free_span_info(merged_spans); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_merge_spans_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_merge_spans PURPOSE Merge new hyperslab spans to existing hyperslab selection USAGE herr_t H5S__hyper_merge_spans(space, new_spans, can_own) H5S_t *space; IN: Dataspace to add new spans to hyperslab selection. H5S_hyper_span_t *new_spans; IN: Span tree of new spans to add to hyperslab selection RETURNS non-negative on success, negative on failure DESCRIPTION Add a set of hyperslab spans to an existing hyperslab selection. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_merge_spans(H5S_t *space, H5S_hyper_span_info_t *new_spans) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity checks */ HDassert(space); HDassert(new_spans); /* If this is the first span tree in the hyperslab selection, just use it */ if (space->select.sel_info.hslab->span_lst == NULL) { space->select.sel_info.hslab->span_lst = new_spans; space->select.sel_info.hslab->span_lst->count++; } /* end if */ else { H5S_hyper_span_info_t *merged_spans; /* Get the merged spans */ if (NULL == (merged_spans = H5S__hyper_merge_spans_helper(space->select.sel_info.hslab->span_lst, new_spans, space->extent.rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTMERGE, FAIL, "can't merge hyperslab spans") /* Free the previous spans */ H5S__hyper_free_span_info(space->select.sel_info.hslab->span_lst); /* Point to the new merged spans */ space->select.sel_info.hslab->span_lst = merged_spans; } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_merge_spans() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_spans_nelem_helper PURPOSE Count the number of elements in a span tree USAGE hsize_t H5S__hyper_spans_nelem_helper(spans, op_info_i, op_gen) const H5S_hyper_span_info_t *spans; IN: Hyperslan span tree to count elements of unsigned op_info_i; IN: Index of op info to use uint64_t op_gen; IN: Operation generation RETURNS Number of elements in span tree on success; negative on failure DESCRIPTION Counts the number of elements described by the spans in a span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__hyper_spans_nelem_helper(H5S_hyper_span_info_t *spans, unsigned op_info_i, uint64_t op_gen) { hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(spans); /* Check if the span tree was already counted */ if (spans->op_info[op_info_i].op_gen == op_gen) /* Just return the # of elements in the already counted span tree */ ret_value = spans->op_info[op_info_i].u.nelmts; else { /* Count the number of elements in the span tree */ const H5S_hyper_span_t *span; /* Hyperslab span */ span = spans->head; if (NULL == span->down) { while (span != NULL) { /* Compute # of elements covered */ ret_value += (span->high - span->low) + 1; /* Advance to next span */ span = span->next; } /* end while */ } /* end if */ else { while (span != NULL) { hsize_t nelmts; /* # of elements covered by current span */ /* Compute # of elements covered */ nelmts = (span->high - span->low) + 1; /* Multiply the size of this span by the total down span elements */ ret_value += nelmts * H5S__hyper_spans_nelem_helper(span->down, op_info_i, op_gen); /* Advance to next span */ span = span->next; } /* end while */ } /* end else */ /* Set the operation generation for this span tree, to avoid re-computing */ spans->op_info[op_info_i].op_gen = op_gen; /* Hold a copy of the # of elements */ spans->op_info[op_info_i].u.nelmts = ret_value; } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_spans_nelem_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_spans_nelem PURPOSE Count the number of elements in a span tree USAGE hsize_t H5S__hyper_spans_nelem(spans) const H5S_hyper_span_info_t *spans; IN: Hyperslan span tree to count elements of RETURNS Number of elements in span tree on success; negative on failure DESCRIPTION Counts the number of elements described by the spans in a span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__hyper_spans_nelem(H5S_hyper_span_info_t *spans) { uint64_t op_gen; /* Operation generation value */ hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(spans); /* Acquire an operation generation value for this operation */ op_gen = H5S__hyper_get_op_gen(); /* Count the number of elements in the span tree */ /* Always use op_info[0] since we own this op_info, so there can be no * simultaneous operations */ ret_value = H5S__hyper_spans_nelem_helper(spans, 0, op_gen); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_spans_nelem() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_add_disjoint_spans PURPOSE Add new hyperslab spans to existing hyperslab selection in the case the new hyperslab spans don't overlap with the existing hyperslab selection USAGE herr_t H5S__hyper_add_disjoint_spans(space, new_spans) H5S_t *space; IN: Dataspace to add new spans to hyperslab selection. H5S_hyper_span_t *new_spans; IN: Span tree of new spans to add to hyperslab selection RETURNS Non-negative on success, negative on failure DESCRIPTION Add a set of hyperslab spans to an existing hyperslab selection. The new spans are required not to overlap with the existing spans in the dataspace's current hyperslab selection in terms of bound box. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_add_disjoint_spans(H5S_t *space, H5S_hyper_span_info_t *new_spans) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space); HDassert(new_spans); /* Update the number of elements in the selection */ space->select.num_elem += H5S__hyper_spans_nelem(new_spans); /* Add the new spans to the existing selection in the dataspace */ if (H5S__hyper_merge_spans(space, new_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't merge hyperslabs") /* Free the memory space for new spans */ H5S__hyper_free_span_info(new_spans); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_add_disjoint_spans */ /*-------------------------------------------------------------------------- NAME H5S__hyper_make_spans PURPOSE Create a span tree USAGE H5S_hyper_span_t *H5S__hyper_make_spans(rank, start, stride, count, block) unsigned rank; IN: # of dimensions of the space const hsize_t *start; IN: Starting location of the hyperslabs const hsize_t *stride; IN: Stride from the beginning of one block to the next const hsize_t *count; IN: Number of blocks const hsize_t *block; IN: Size of hyperslab block RETURNS Pointer to new span tree on success, NULL on failure DESCRIPTION Generates a new span tree for the hyperslab parameters specified. Each span tree has a list of the elements spanned in each dimension, with each span node containing a pointer to the list of spans in the next dimension down. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5S_hyper_span_info_t * H5S__hyper_make_spans(unsigned rank, const hsize_t *start, const hsize_t *stride, const hsize_t *count, const hsize_t *block) { H5S_hyper_span_info_t *down = NULL; /* Pointer to spans in next dimension down */ H5S_hyper_span_t * last_span; /* Current position in hyperslab span list */ H5S_hyper_span_t * head = NULL; /* Head of new hyperslab span list */ int i; /* Counters */ H5S_hyper_span_info_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(rank > 0); HDassert(start); HDassert(stride); HDassert(count); HDassert(block); /* Start creating spans in fastest changing dimension */ for (i = (int)(rank - 1); i >= 0; i--) { hsize_t curr_low, curr_high; /* Current low & high values */ hsize_t dim_stride; /* Current dim's stride */ unsigned u; /* Local index variable */ /* Sanity check */ if (0 == count[i]) HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, NULL, "count == 0 is invalid") /* Start a new list in this dimension */ head = NULL; last_span = NULL; /* Generate all the span segments for this dimension */ curr_low = start[i]; curr_high = start[i] + (block[i] - 1); dim_stride = stride[i]; for (u = 0; u < count[i]; u++, curr_low += dim_stride, curr_high += dim_stride) { H5S_hyper_span_t *span; /* New hyperslab span */ /* Allocate a span node */ if (NULL == (span = H5FL_MALLOC(H5S_hyper_span_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Set the span's basic information */ span->low = curr_low; span->high = curr_high; span->next = NULL; /* Set the information for the next dimension down's spans */ /* (Will be NULL for fastest changing dimension) */ span->down = down; /* Append to the list of spans in this dimension */ if (head == NULL) head = span; else last_span->next = span; /* Move current pointer */ last_span = span; } /* end for */ /* Increment ref. count of shared span */ if (down != NULL) down->count = (unsigned)count[i]; /* Allocate a span info node */ if (NULL == (down = H5S__hyper_new_span_info(rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, NULL, "can't allocate hyperslab span") /* Keep the pointer to the next dimension down's completed list */ down->head = head; /* Keep the tail pointer to the next dimension down's completed list */ down->tail = last_span; /* Set the low & high bounds for this dimension */ down->low_bounds[0] = down->head->low; down->high_bounds[0] = down->tail->high; /* Copy bounds from lower dimensions */ /* (head & tail pointers share lower dimensions, so using either is OK) */ if (head->down) { H5MM_memcpy(&down->low_bounds[1], &head->down->low_bounds[0], sizeof(hsize_t) * ((rank - 1) - (unsigned)i)); H5MM_memcpy(&down->high_bounds[1], &head->down->high_bounds[0], sizeof(hsize_t) * ((rank - 1) - (unsigned)i)); } /* end if */ } /* end for */ /* Indicate that there is a pointer to this tree */ if (down) down->count = 1; /* Success! Return the head of the list in the slowest changing dimension */ ret_value = down; done: /* cleanup if error (ret_value will be NULL) */ if (!ret_value) { if (head || down) { if (head && down) if (down->head != head) down = NULL; do { if (down) { head = down->head; down = (H5S_hyper_span_info_t *)H5FL_ARR_FREE(hbounds_t, down); } /* end if */ down = head->down; while (head) { last_span = head->next; head = H5FL_FREE(H5S_hyper_span_t, head); head = last_span; } /* end while */ } while (down); } /* end if */ } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_make_spans() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_update_diminfo PURPOSE Attempt to update optimized hyperslab information quickly. (It can be recovered with regular selection). If this algorithm cannot determine the optimized dimension info quickly, this function will simply mark it as invalid and unknown if it can be built (H5S_DIMINFO_VALID_NO), so H5S__hyper_rebuild can be run later to determine for sure. USAGE herr_t H5S__hyper_update_diminfo(space, op, new_hyper_diminfo) H5S_t *space; IN: Dataspace to check H5S_seloper_t op; IN: The operation being performed on the selection const H5S_hyper_dim_t new_hyper_diminfo; IN: The new selection that is being combined with the current RETURNS >=0 on success, <0 on failure DESCRIPTION Examine the span tree for a hyperslab selection and rebuild the start/stride/count/block information for the selection, if possible. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_update_diminfo(H5S_t *space, H5S_seloper_t op, const H5S_hyper_dim_t *new_hyper_diminfo) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Check args */ HDassert(space); HDassert(new_hyper_diminfo); /* Check for conditions that prevent us from using the fast algorithm here */ /* (and instead require H5S__hyper_rebuild) */ if (!((op == H5S_SELECT_OR) || (op == H5S_SELECT_XOR)) || space->select.sel_info.hslab->diminfo_valid != H5S_DIMINFO_VALID_YES || !space->select.sel_info.hslab->span_lst->head) space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; else { H5S_hyper_dim_t tmp_diminfo[H5S_MAX_RANK]; /* Temporary dimension info */ hbool_t found_nonidentical_dim = FALSE; unsigned curr_dim; /* Copy current diminfo.opt values */ H5MM_memcpy(tmp_diminfo, space->select.sel_info.hslab->diminfo.opt, sizeof(tmp_diminfo)); /* Loop over dimensions */ for (curr_dim = 0; curr_dim < space->extent.rank; curr_dim++) { /* Check for this being identical */ if ((tmp_diminfo[curr_dim].start != new_hyper_diminfo[curr_dim].start) || (tmp_diminfo[curr_dim].stride != new_hyper_diminfo[curr_dim].stride) || (tmp_diminfo[curr_dim].count != new_hyper_diminfo[curr_dim].count) || (tmp_diminfo[curr_dim].block != new_hyper_diminfo[curr_dim].block)) { hsize_t high_start, high_count, high_block; /* The start, count & block values for the higher block */ /* Dimension is not identical */ /* Check if we already found a nonidentical dim - only one is * allowed */ if (found_nonidentical_dim) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Check that strides are the same, or count is 1 for one of the * slabs */ if ((tmp_diminfo[curr_dim].stride != new_hyper_diminfo[curr_dim].stride) && (tmp_diminfo[curr_dim].count > 1) && (new_hyper_diminfo[curr_dim].count > 1)) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Patch tmp_diminfo.stride if its count is 1 */ if ((tmp_diminfo[curr_dim].count == 1) && (new_hyper_diminfo[curr_dim].count > 1)) tmp_diminfo[curr_dim].stride = new_hyper_diminfo[curr_dim].stride; /* Determine lowest start, and set tmp_diminfo.start, count and * block to use the lowest, and high_start, high_count and * high_block to use the highest */ if (tmp_diminfo[curr_dim].start < new_hyper_diminfo[curr_dim].start) { high_start = new_hyper_diminfo[curr_dim].start; high_count = new_hyper_diminfo[curr_dim].count; high_block = new_hyper_diminfo[curr_dim].block; } /* end if */ else { high_start = tmp_diminfo[curr_dim].start; tmp_diminfo[curr_dim].start = new_hyper_diminfo[curr_dim].start; high_count = tmp_diminfo[curr_dim].count; tmp_diminfo[curr_dim].count = new_hyper_diminfo[curr_dim].count; high_block = tmp_diminfo[curr_dim].block; tmp_diminfo[curr_dim].block = new_hyper_diminfo[curr_dim].block; } /* end else */ /* If count is 1 for both slabs, take different actions */ if ((tmp_diminfo[curr_dim].count == 1) && (high_count == 1)) { /* Check for overlap */ if ((tmp_diminfo[curr_dim].start + tmp_diminfo[curr_dim].block) > high_start) { /* Check operation type */ if (op == H5S_SELECT_OR) /* Merge blocks */ tmp_diminfo[curr_dim].block = ((high_start + high_block) >= (tmp_diminfo[curr_dim].start + tmp_diminfo[curr_dim].block)) ? (high_start + high_block - tmp_diminfo[curr_dim].start) : tmp_diminfo[curr_dim].block; else { /* Block values must be the same */ if (tmp_diminfo[curr_dim].block != high_block) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* XOR - overlap creates 2 blocks */ tmp_diminfo[curr_dim].stride = high_block; tmp_diminfo[curr_dim].count = 2; tmp_diminfo[curr_dim].block = high_start - tmp_diminfo[curr_dim].start; } /* end else */ } /* end if */ else if ((tmp_diminfo[curr_dim].start + tmp_diminfo[curr_dim].block) == high_start) /* Blocks border, merge them */ tmp_diminfo[curr_dim].block += high_block; else { /* Distinct blocks */ /* Block values must be the same */ if (tmp_diminfo[curr_dim].block != high_block) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Create strided selection */ tmp_diminfo[curr_dim].stride = high_start - tmp_diminfo[curr_dim].start; tmp_diminfo[curr_dim].count = 2; } /* end else */ } /* end if */ else { /* Check if block values are the same */ if (tmp_diminfo[curr_dim].block != new_hyper_diminfo[curr_dim].block) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Check phase of strides */ if ((tmp_diminfo[curr_dim].start % tmp_diminfo[curr_dim].stride) != (new_hyper_diminfo[curr_dim].start % tmp_diminfo[curr_dim].stride)) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Check operation type */ if (op == H5S_SELECT_OR) { /* Make sure the slabs border or overlap */ if (high_start > (tmp_diminfo[curr_dim].start + (tmp_diminfo[curr_dim].count * tmp_diminfo[curr_dim].stride))) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ } /* end if */ else /* XOR: Make sure the slabs border */ if (high_start != (tmp_diminfo[curr_dim].start + (tmp_diminfo[curr_dim].count * tmp_diminfo[curr_dim].stride))) { space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; break; } /* end if */ /* Set count for combined selection */ tmp_diminfo[curr_dim].count = ((high_start - tmp_diminfo[curr_dim].start) / tmp_diminfo[curr_dim].stride) + high_count; } /* end else */ /* Indicate that we found a nonidentical dim */ found_nonidentical_dim = TRUE; } /* end if */ } /* end for */ /* Check if we succeeded, if so, set the new diminfo values */ if (space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) for (curr_dim = 0; curr_dim < space->extent.rank; curr_dim++) { hsize_t tmp_high_bound; /* Set the new diminfo values */ space->select.sel_info.hslab->diminfo.app[curr_dim].start = space->select.sel_info.hslab->diminfo.opt[curr_dim].start = tmp_diminfo[curr_dim].start; HDassert(tmp_diminfo[curr_dim].stride > 0); space->select.sel_info.hslab->diminfo.app[curr_dim].stride = space->select.sel_info.hslab->diminfo.opt[curr_dim].stride = tmp_diminfo[curr_dim].stride; HDassert(tmp_diminfo[curr_dim].count > 0); space->select.sel_info.hslab->diminfo.app[curr_dim].count = space->select.sel_info.hslab->diminfo.opt[curr_dim].count = tmp_diminfo[curr_dim].count; HDassert(tmp_diminfo[curr_dim].block > 0); space->select.sel_info.hslab->diminfo.app[curr_dim].block = space->select.sel_info.hslab->diminfo.opt[curr_dim].block = tmp_diminfo[curr_dim].block; /* Check for updating the low & high bounds */ if (tmp_diminfo[curr_dim].start < space->select.sel_info.hslab->diminfo.low_bounds[curr_dim]) space->select.sel_info.hslab->diminfo.low_bounds[curr_dim] = tmp_diminfo[curr_dim].start; tmp_high_bound = tmp_diminfo[curr_dim].start + (tmp_diminfo[curr_dim].block - 1) + (tmp_diminfo[curr_dim].stride * (tmp_diminfo[curr_dim].count - 1)); if (tmp_high_bound > space->select.sel_info.hslab->diminfo.low_bounds[curr_dim]) space->select.sel_info.hslab->diminfo.high_bounds[curr_dim] = tmp_high_bound; } /* end for */ } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_update_diminfo() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_rebuild_helper PURPOSE Helper routine to rebuild optimized hyperslab information if possible. (It can be recovered with regular selection) USAGE herr_t H5S__hyper_rebuild_helper(space) const H5S_hyper_span_t *spans; IN: Portion of span tree to check H5S_hyper_dim_t span_slab_info[]; OUT: Rebuilt section of hyperslab description RETURNS TRUE/FALSE for hyperslab selection rebuilt DESCRIPTION Examine the span tree for a hyperslab selection and rebuild the start/stride/count/block information for the selection, if possible. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS To be able to recover the optimized information, the span tree must conform to span tree able to be generated from a single H5S_SELECT_SET operation. EXAMPLES REVISION LOG KY, 2005/9/22 --------------------------------------------------------------------------*/ static hbool_t H5S__hyper_rebuild_helper(const H5S_hyper_span_info_t *spans, H5S_hyper_dim_t span_slab_info[]) { const H5S_hyper_span_t *span; /* Hyperslab span */ const H5S_hyper_span_t *prev_span; /* Previous span in list */ hsize_t start; /* Starting element for this dimension */ hsize_t stride; /* Stride for this dimension */ hsize_t block; /* Block size for this dimension */ hsize_t prev_low; /* Low bound for previous span */ size_t spancount; /* Number of spans encountered in this dimension */ hbool_t ret_value = TRUE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity check */ HDassert(spans); /* Initialization */ span = spans->head; stride = 1; prev_low = 0; spancount = 0; /* Get "canonical" down span information */ if (span->down) /* Go to the next down span and check whether the selection can be rebuilt */ if (!H5S__hyper_rebuild_helper(span->down, &span_slab_info[1])) HGOTO_DONE(FALSE) /* Assign the initial starting point & block size for this dimension */ start = span->low; block = (span->high - span->low) + 1; /* Loop the spans */ prev_span = NULL; while (span) { if (spancount > 0) { hsize_t curr_stride; /* Current stride from previous span */ hsize_t curr_block; /* Block size of current span */ /* Sanity check */ HDassert(prev_span); /* Check that down spans match current slab info */ /* (Can skip check if previous span's down pointer is same as current one) */ if (span->down && prev_span->down != span->down) if (!H5S__hyper_cmp_spans(span->down, prev_span->down)) HGOTO_DONE(FALSE) /* Obtain values for stride and block */ curr_stride = span->low - prev_low; curr_block = (span->high - span->low) + 1; /* Compare stride and block for this span. To compare stride, * three spans are needed. Account for the first two spans. */ if (curr_block != block) HGOTO_DONE(FALSE) if (spancount > 1) { if (stride != curr_stride) HGOTO_DONE(FALSE) } /* end if */ else stride = curr_stride; } /* end if */ /* Keep current starting point */ prev_low = span->low; /* Advance to next span */ prev_span = span; span = span->next; spancount++; } /* end while */ /* Save the span information. */ span_slab_info[0].start = start; span_slab_info[0].count = spancount; span_slab_info[0].block = block; span_slab_info[0].stride = stride; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_rebuild_helper() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_rebuild PURPOSE Rebuild optimized hyperslab information if possible. (It can be recovered with regular selection) USAGE void H5S__hyper_rebuild(space) H5S_t *space; IN: Dataspace to check RETURNS None DESCRIPTION Examine the span tree for a hyperslab selection and rebuild a regular start/stride/count/block hyperslab selection, if possible. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS To be able to recover the optimized information, the span tree must conform to span tree able to be generated from a single H5S_SELECT_SET operation. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ void H5S__hyper_rebuild(H5S_t *space) { H5S_hyper_dim_t rebuilt_slab_info[H5S_MAX_RANK]; FUNC_ENTER_PACKAGE_NOERR /* Check args */ HDassert(space); HDassert(space->select.sel_info.hslab->span_lst); /* Check whether the slab can be rebuilt */ /* (Only regular selection can be rebuilt. If yes, fill in correct values) */ if (FALSE == H5S__hyper_rebuild_helper(space->select.sel_info.hslab->span_lst, rebuilt_slab_info)) space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_IMPOSSIBLE; else { /* Set the dimension info & bounds for the dataspace, from the rebuilt info */ H5MM_memcpy(space->select.sel_info.hslab->diminfo.app, rebuilt_slab_info, sizeof(rebuilt_slab_info)); H5MM_memcpy(space->select.sel_info.hslab->diminfo.opt, rebuilt_slab_info, sizeof(rebuilt_slab_info)); H5MM_memcpy(space->select.sel_info.hslab->diminfo.low_bounds, space->select.sel_info.hslab->span_lst->low_bounds, sizeof(hsize_t) * space->extent.rank); H5MM_memcpy(space->select.sel_info.hslab->diminfo.high_bounds, space->select.sel_info.hslab->span_lst->high_bounds, sizeof(hsize_t) * space->extent.rank); space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_YES; } /* end else */ FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_rebuild() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_generate_spans PURPOSE Create span tree for a regular hyperslab selection USAGE herr_t H5S__hyper_generate_spans(space) H5S_t *space; IN/OUT: Pointer to dataspace RETURNS Non-negative on success, negative on failure DESCRIPTION Create a span tree representation of a regular hyperslab selection and add it to the information for the hyperslab selection. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_generate_spans(H5S_t *space) { hsize_t tmp_start[H5S_MAX_RANK]; /* Temporary start information */ hsize_t tmp_stride[H5S_MAX_RANK]; /* Temporary stride information */ hsize_t tmp_count[H5S_MAX_RANK]; /* Temporary count information */ hsize_t tmp_block[H5S_MAX_RANK]; /* Temporary block information */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC HDassert(space); HDassert(H5S_GET_SELECT_TYPE(space) == H5S_SEL_HYPERSLABS); /* Get the diminfo */ for (u = 0; u < space->extent.rank; u++) { /* Check for unlimited dimension and return error */ /* These should be able to be converted to assertions once everything * that calls this function checks for unlimited selections first * (especially the new hyperslab API) -NAF */ if (space->select.sel_info.hslab->diminfo.opt[u].count == H5S_UNLIMITED) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "can't generate spans with unlimited count") if (space->select.sel_info.hslab->diminfo.opt[u].block == H5S_UNLIMITED) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "can't generate spans with unlimited block") tmp_start[u] = space->select.sel_info.hslab->diminfo.opt[u].start; tmp_stride[u] = space->select.sel_info.hslab->diminfo.opt[u].stride; tmp_count[u] = space->select.sel_info.hslab->diminfo.opt[u].count; tmp_block[u] = space->select.sel_info.hslab->diminfo.opt[u].block; } /* end for */ /* Build the hyperslab information also */ if (H5S__generate_hyperslab(space, H5S_SELECT_SET, tmp_start, tmp_stride, tmp_count, tmp_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't generate hyperslabs") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_generate_spans() */ /*-------------------------------------------------------------------------- NAME H5S__check_spans_overlap PURPOSE Check if two selections' bounds overlap. USAGE hbool_t H5S__check_spans_overlap(spans1, spans2) const H5S_hyper_span_info_t *spans1; IN: Second span list const H5S_hyper_span_info_t *spans2; IN: Second span list RETURNS TRUE for overlap, FALSE for no overlap PROGRAMMER Quincey Koziol - January 24, 2019 GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static H5_ATTR_PURE hbool_t H5S__check_spans_overlap(const H5S_hyper_span_info_t *spans1, const H5S_hyper_span_info_t *spans2) { hbool_t ret_value = FALSE; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Sanity checks */ HDassert(spans1); HDassert(spans2); /* Use low & high bounds to try to avoid spinning through the span lists */ if (H5S_RANGE_OVERLAP(spans1->low_bounds[0], spans1->high_bounds[0], spans2->low_bounds[0], spans2->high_bounds[0])) { H5S_hyper_span_t *span1, *span2; /* Hyperslab spans */ /* Walk over spans, comparing them for overlap */ span1 = spans1->head; span2 = spans2->head; while (span1 && span2) { /* Check current two spans for overlap */ if (H5S_RANGE_OVERLAP(span1->low, span1->high, span2->low, span2->high)) { /* Check for spans in lowest dimension already */ if (span1->down) { /* Sanity check */ HDassert(span2->down); /* Check lower dimensions for overlap */ if (H5S__check_spans_overlap(span1->down, span2->down)) HGOTO_DONE(TRUE); } /* end if */ else HGOTO_DONE(TRUE); } /* end if */ /* Advance one of the spans */ if (span1->high <= span2->high) { /* Advance span1, unless it would be off the list and span2 has more nodes */ if (NULL == span1->next && NULL != span2->next) span2 = span2->next; else span1 = span1->next; } /* end if */ else { /* Advance span2, unless it would be off the list and span1 has more nodes */ if (NULL == span2->next && NULL != span1->next) span1 = span1->next; else span2 = span2->next; } /* end else */ } /* end while */ /* Make certain we've exhausted our comparisons */ HDassert((NULL == span1 && (NULL != span2 && NULL == span2->next)) || ((NULL != span1 && NULL == span1->next) && NULL == span2)); } /* end of */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__check_spans_overlap() */ /*-------------------------------------------------------------------------- NAME H5S__fill_in_new_space PURPOSE Combine two span lists, one from an existing dataspace and the other from input arguments, into a new selection depending on the selection operator. The new selection is put into a resulting dataspace which could be allocated inside the function. USAGE herr_t H5S__fill_in_new_space(space1, op, space2_span_lst, can_own_span2, span2_owned, result) H5S_t *space1; IN: Dataspace containing the first span list H5S_seloper_t op; IN: Selection operation H5S_hyper_span_info_t *space2_span_lst; IN: Second span list hbool_t can_own_span2; IN: Indicates whether the 2nd span list could be owned by the result. If not, the 2nd span list has to be copied. hbool_t *span2_owned; OUT: Indicates if the 2nd span list is actually owned H5S_t **result; OUT: The dataspace containing the the new selection. It could be same with the 1st dataspace. RETURNS Non-negative on success, negative on failure PROGRAMMER Chao Mei July 8, 2011 GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__fill_in_new_space(H5S_t *space1, H5S_seloper_t op, H5S_hyper_span_info_t *space2_span_lst, hbool_t can_own_span2, hbool_t *span2_owned, hbool_t *updated_spans, H5S_t **result) { H5S_hyper_span_info_t *a_not_b = NULL; /* Span tree for hyperslab spans in old span tree and not in new span tree */ H5S_hyper_span_info_t *a_and_b = NULL; /* Span tree for hyperslab spans in both old and new span trees */ H5S_hyper_span_info_t *b_not_a = NULL; /* Span tree for hyperslab spans in new span tree and not in old span tree */ hbool_t overlapped = FALSE; /* Whether selections overlap */ hbool_t is_result_new = FALSE; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC HDassert(space1); HDassert(space2_span_lst); HDassert(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA); /* The result is either a to-be-created space or an empty one */ HDassert(*result == NULL || *result == space1); HDassert(space1->select.sel_info.hslab->span_lst); HDassert(span2_owned); /* Reset flags to return */ *span2_owned = FALSE; *updated_spans = FALSE; /* The result shares the same info from space1 */ if (*result == NULL) { if (NULL == ((*result) = H5S_copy(space1, TRUE, TRUE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to copy dataspace") space1->select.sel_info.hslab->span_lst->count--; (*result)->select.sel_info.hslab->span_lst = NULL; is_result_new = TRUE; } /* end if */ /* Check both spaces to see if they overlap */ overlapped = H5S__check_spans_overlap(space1->select.sel_info.hslab->span_lst, space2_span_lst); if (!overlapped) { switch (op) { case H5S_SELECT_OR: case H5S_SELECT_XOR: /* Add the new disjoint spans to the space */ /* Copy of space1's spans to *result, and another copy of space2's spans */ if (is_result_new) (*result)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span(space1->select.sel_info.hslab->span_lst, space1->extent.rank); if (!can_own_span2) { b_not_a = H5S__hyper_copy_span(space2_span_lst, space1->extent.rank); if (H5S__hyper_add_disjoint_spans(*result, b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't append hyperslabs") /* The new_spans are now owned by 'space', so they should not be released */ b_not_a = NULL; } /* end if */ else { if (H5S__hyper_add_disjoint_spans(*result, space2_span_lst) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't append hyperslabs") *span2_owned = TRUE; } /* end else */ /* Indicate that the spans changed */ *updated_spans = TRUE; break; case H5S_SELECT_AND: /* Convert *result to "none" selection */ if (H5S_select_none(*result) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") HGOTO_DONE(SUCCEED); case H5S_SELECT_NOTB: /* Copy space1's spans to *result */ if (is_result_new) (*result)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span(space1->select.sel_info.hslab->span_lst, space1->extent.rank); /* Indicate that the spans changed */ *updated_spans = TRUE; break; case H5S_SELECT_NOTA: if (!is_result_new) { HDassert(space1 == *result); /* Free the current selection */ H5S__hyper_free_span_info(space1->select.sel_info.hslab->span_lst); space1->select.sel_info.hslab->span_lst = NULL; } /* end if */ /* Copy space2's spans to *result */ if (!can_own_span2) (*result)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span(space2_span_lst, space1->extent.rank); else { (*result)->select.sel_info.hslab->span_lst = space2_span_lst; *span2_owned = TRUE; } /* end else */ /* Reset the number of items in selection */ (*result)->select.num_elem = H5S__hyper_spans_nelem(space2_span_lst); /* Indicate that the spans changed */ *updated_spans = TRUE; break; case H5S_SELECT_NOOP: case H5S_SELECT_SET: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ } /* end if */ else { unsigned selector = 0; /* Select which clipping spans to generate */ /* Generate mask for clip operation depending on the op */ switch (op) { case H5S_SELECT_OR: /* a + b_not_a */ selector = H5S_HYPER_COMPUTE_B_NOT_A; break; case H5S_SELECT_XOR: /* a_not_b + b_not_a */ selector = H5S_HYPER_COMPUTE_A_NOT_B | H5S_HYPER_COMPUTE_B_NOT_A; break; case H5S_SELECT_AND: /* a_and_b */ selector = H5S_HYPER_COMPUTE_A_AND_B; break; case H5S_SELECT_NOTB: /* a_not_b */ selector = H5S_HYPER_COMPUTE_A_NOT_B; break; case H5S_SELECT_NOTA: /* b_not_a */ selector = H5S_HYPER_COMPUTE_B_NOT_A; break; case H5S_SELECT_NOOP: case H5S_SELECT_SET: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ /* Generate lists of spans which overlap and don't overlap */ if (H5S__hyper_clip_spans(space1->select.sel_info.hslab->span_lst, space2_span_lst, selector, space1->extent.rank, &a_not_b, &a_and_b, &b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't clip hyperslab information") switch (op) { case H5S_SELECT_OR: if (is_result_new) (*result)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span(space1->select.sel_info.hslab->span_lst, space1->extent.rank); break; case H5S_SELECT_AND: case H5S_SELECT_XOR: case H5S_SELECT_NOTB: case H5S_SELECT_NOTA: if (!is_result_new) { HDassert(space1 == *result); /* Free the current selection */ H5S__hyper_free_span_info(space1->select.sel_info.hslab->span_lst); space1->select.sel_info.hslab->span_lst = NULL; } /* end if */ /* Reset the number of items in selection */ /* (Will be set below) */ (*result)->select.num_elem = 0; break; case H5S_SELECT_NOOP: case H5S_SELECT_SET: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ /* Check if there are any non-overlapped selections */ if (a_not_b) { /* Other than OR, the span_lst is set to NULL. And in OR, * a_not_b is not needed */ HDassert(NULL == (*result)->select.sel_info.hslab->span_lst); /* The results dataspace takes ownership of the spans */ /* (Since it must be NULL) */ (*result)->select.sel_info.hslab->span_lst = a_not_b; /* Update the number of elements in current selection */ (*result)->select.num_elem = H5S__hyper_spans_nelem(a_not_b); /* Indicate that the spans were updated */ *updated_spans = TRUE; /* Indicate that the a_not_b spans are owned */ a_not_b = NULL; } /* end if */ if (a_and_b) { /** * 1. Other than OR, the span_lst is set to NULL. And in OR, * a_and_b is not needed * 2. a_not_b will never be computed together with a_and_b * because merging these two equals to a. */ HDassert(NULL == (*result)->select.sel_info.hslab->span_lst); /* The results dataspace takes ownership of the spans */ /* (Since it must be NULL) */ (*result)->select.sel_info.hslab->span_lst = a_and_b; /* Update the number of elements in current selection */ (*result)->select.num_elem = H5S__hyper_spans_nelem(a_and_b); /* Indicate that the spans were updated */ *updated_spans = TRUE; /* Indicate that the a_and_b spans are owned */ a_and_b = NULL; } /* end if */ if (b_not_a) { /* Merge the b_not_a spans into the result dataspace */ if (H5S__hyper_merge_spans(*result, b_not_a) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't insert hyperslabs") /* Update the number of elements in current selection */ (*result)->select.num_elem += H5S__hyper_spans_nelem(b_not_a); /* Indicate that the spans were updated */ *updated_spans = TRUE; } /* end if */ } /* end else for the case the new span overlaps with the old (i.e. space) */ /* Check if the spans weren't updated, and reset selection if so */ if (!*updated_spans) { /* If updated_spans remains FALSE as in this branch, it means the * result has been cleared in XOR / AND / NOTB / NOTA cases, and the * result is a copy of the dataspace in the OR case. * * If two dataspaces have generated any of the three clipped * span trees (i.e. a_not_b, a_and_b, and b_not_a), the * updated_spans must be TRUE. */ if (H5S_SELECT_OR != op) { /* Convert *result to "none" selection */ if (H5S_select_none(*result) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") } /* end else */ } /* end if */ done: /* Free resources */ if (a_not_b) H5S__hyper_free_span_info(a_not_b); if (a_and_b) H5S__hyper_free_span_info(a_and_b); if (b_not_a) H5S__hyper_free_span_info(b_not_a); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__fill_in_new_space() */ /*------------------------------------------------------------------------- * Function: H5S__generate_hyperlab * * Purpose: Generate hyperslab information from H5S_select_hyperslab() * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * Tuesday, September 12, 2000 * *------------------------------------------------------------------------- */ static herr_t H5S__generate_hyperslab(H5S_t *space, H5S_seloper_t op, const hsize_t start[], const hsize_t stride[], const hsize_t count[], const hsize_t block[]) { H5S_hyper_span_info_t *new_spans = NULL; /* Span tree for new hyperslab */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space); HDassert(op > H5S_SELECT_NOOP && op < H5S_SELECT_INVALID); HDassert(start); HDassert(stride); HDassert(count); HDassert(block); /* Generate span tree for new hyperslab information */ if (NULL == (new_spans = H5S__hyper_make_spans(space->extent.rank, start, stride, count, block))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't create hyperslab information") /* Generate list of blocks to add/remove based on selection operation */ if (op == H5S_SELECT_SET) { /* Free current selection */ if (NULL != space->select.sel_info.hslab->span_lst) H5S__hyper_free_span_info(space->select.sel_info.hslab->span_lst); /* Set the hyperslab selection to the new span tree */ space->select.sel_info.hslab->span_lst = new_spans; /* Set the number of elements in current selection */ space->select.num_elem = H5S__hyper_spans_nelem(new_spans); /* Indicate that the new_spans are owned */ new_spans = NULL; } /* end if */ else { hbool_t new_spans_owned = FALSE; hbool_t updated_spans = FALSE; /* Generate new spans for space */ if (H5S__fill_in_new_space(space, op, new_spans, TRUE, &new_spans_owned, &updated_spans, &space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't generate the specified hyperslab") /* Check if the spans were updated by H5S__fill_in_new_space */ if (updated_spans) { H5S_hyper_dim_t new_hyper_diminfo[H5S_MAX_RANK]; unsigned u; /* Local index variable */ /* Sanity check */ HDassert(space->select.sel_info.hslab->span_lst->head); /* Build diminfo struct */ for (u = 0; u < space->extent.rank; u++) { new_hyper_diminfo[u].start = start[u]; new_hyper_diminfo[u].stride = stride[u]; new_hyper_diminfo[u].count = count[u]; new_hyper_diminfo[u].block = block[u]; } /* end for */ /* Update space's dim info */ if (H5S__hyper_update_diminfo(space, op, new_hyper_diminfo) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOUNT, FAIL, "can't update hyperslab info") } /* end if */ /* Indicate that the new_spans are owned, there's no need to free */ if (new_spans_owned) new_spans = NULL; } /* end else */ done: if (new_spans) H5S__hyper_free_span_info(new_spans); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__generate_hyperslab() */ /*------------------------------------------------------------------------- * Function: H5S__set_regular_hyperslab * * Purpose: Set a regular hyperslab * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * Thursday, October 2, 2014 * *------------------------------------------------------------------------- */ herr_t H5S__set_regular_hyperslab(H5S_t *space, const hsize_t start[], const hsize_t *app_stride, const hsize_t app_count[], const hsize_t *app_block, const hsize_t *opt_stride, const hsize_t opt_count[], const hsize_t *opt_block) { unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space); HDassert(start); HDassert(app_stride); HDassert(app_count); HDassert(app_block); HDassert(opt_stride); HDassert(opt_count); HDassert(opt_block); /* If we are setting a new selection, remove current selection first */ if (H5S_SELECT_RELEASE(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't release selection") /* Allocate space for the hyperslab selection information */ if (NULL == (space->select.sel_info.hslab = H5FL_MALLOC(H5S_hyper_sel_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab info") /* Set the diminfo */ space->select.num_elem = 1; space->select.sel_info.hslab->unlim_dim = -1; for (u = 0; u < space->extent.rank; u++) { /* Set application and optimized hyperslab info */ space->select.sel_info.hslab->diminfo.app[u].start = start[u]; space->select.sel_info.hslab->diminfo.app[u].stride = app_stride[u]; space->select.sel_info.hslab->diminfo.app[u].count = app_count[u]; space->select.sel_info.hslab->diminfo.app[u].block = app_block[u]; space->select.sel_info.hslab->diminfo.opt[u].start = start[u]; space->select.sel_info.hslab->diminfo.opt[u].stride = opt_stride[u]; space->select.sel_info.hslab->diminfo.opt[u].count = opt_count[u]; space->select.sel_info.hslab->diminfo.opt[u].block = opt_block[u]; /* Update # of elements selected */ space->select.num_elem *= (opt_count[u] * opt_block[u]); /* Set low bound of bounding box for the hyperslab selection */ space->select.sel_info.hslab->diminfo.low_bounds[u] = start[u]; /* Check for unlimited dimension & set high bound */ if ((app_count[u] == H5S_UNLIMITED) || (app_block[u] == H5S_UNLIMITED)) { space->select.sel_info.hslab->unlim_dim = (int)u; space->select.sel_info.hslab->diminfo.high_bounds[u] = H5S_UNLIMITED; } /* end if */ else space->select.sel_info.hslab->diminfo.high_bounds[u] = start[u] + opt_stride[u] * (opt_count[u] - 1) + (opt_block[u] - 1); } /* end for */ /* Handle unlimited selections */ if (space->select.sel_info.hslab->unlim_dim >= 0) { /* Calculate num_elem_non_unlim */ space->select.sel_info.hslab->num_elem_non_unlim = (hsize_t)1; for (u = 0; u < space->extent.rank; u++) if ((int)u != space->select.sel_info.hslab->unlim_dim) space->select.sel_info.hslab->num_elem_non_unlim *= (opt_count[u] * opt_block[u]); /* Update num_elem */ space->select.num_elem = H5S_UNLIMITED; } /* end if */ /* Indicate that the dimension information is valid */ space->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_YES; /* Indicate that there's no slab information */ space->select.sel_info.hslab->span_lst = NULL; /* Set selection type */ space->select.type = H5S_sel_hyper; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__set_regular_hyperslab() */ /*------------------------------------------------------------------------- * Function: H5S__hyper_regular_and_single_block * * Purpose: Optimized routine to perform "AND" operation of a single * block against a regular hyperslab selection. * * Note: This algorithm is invoked when constructing the chunk map * and a regular hyperslab is selected in the file's dataspace. * * Return: Non-negative on success / Negative on failure * * Programmer: Quincey Koziol * Saturday, February 9, 2019 * *------------------------------------------------------------------------- */ static herr_t H5S__hyper_regular_and_single_block(H5S_t *space, const hsize_t start[], const hsize_t block[]) { hsize_t select_end, block_end; /* End of block & selection */ hbool_t single_block; /* Whether the selection is a single block */ hbool_t overlap; /* Whether block & selection overlap */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space); HDassert(start); HDassert(block); /* Check for single block selection in dataspace */ single_block = TRUE; for (u = 0; u < space->extent.rank; u++) if (1 != space->select.sel_info.hslab->diminfo.opt[u].count) { single_block = FALSE; break; } /* end if */ /* Perform different optimizations, based on type of regular selection */ if (single_block) { hsize_t new_start[H5S_MAX_RANK]; /* New starting coordinate */ hsize_t new_block[H5S_MAX_RANK]; /* New block size */ /* Check for overlap and compute new start offset & block sizes */ overlap = TRUE; for (u = 0; u < space->extent.rank; u++) { /* Compute the end of the selection & block in this dimension */ select_end = space->select.sel_info.hslab->diminfo.high_bounds[u]; block_end = (start[u] + block[u]) - 1; /* Check for overlap */ if (!H5S_RANGE_OVERLAP(space->select.sel_info.hslab->diminfo.opt[u].start, select_end, start[u], block_end)) { overlap = FALSE; break; } /* end if */ /* Set new start & block size in this dimension */ new_start[u] = MAX(space->select.sel_info.hslab->diminfo.opt[u].start, start[u]); new_block[u] = (MIN(select_end, block_end) - new_start[u]) + 1; } /* end for */ /* Check for overlap of selection & block */ if (overlap) { /* Set selection to regular hyperslab */ if (H5S__set_regular_hyperslab(space, new_start, H5S_hyper_ones_g, H5S_hyper_ones_g, new_block, H5S_hyper_ones_g, H5S_hyper_ones_g, new_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't set regular hyperslab selection") } /* end if */ else /* Selection & block don't overlap, set to "none" selection */ if (H5S_select_none(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") } /* end if */ else { hsize_t new_start[H5S_MAX_RANK]; /* New start for hyperslab selection */ hsize_t new_count[H5S_MAX_RANK]; /* New count for hyperslab selection */ hsize_t stride[H5S_MAX_RANK]; /* Stride for hyperslab selection */ hsize_t new_block[H5S_MAX_RANK]; /* New block for hyperslab selection */ hbool_t partial_first_span; /* Whether first span in intersection is partial */ hbool_t partial_last_span; /* Whether last span in intersection is partial */ /* Iterate over selection, checking for overlap and computing first / last * span that intersects with the block. */ overlap = TRUE; partial_first_span = FALSE; partial_last_span = FALSE; for (u = 0; u < space->extent.rank; u++) { hsize_t first_span_start, first_span_end; /* Start / end of first span */ hsize_t last_span_start, last_span_end; /* Start / end of last span */ hsize_t nstride; /* Number of strides into the selection */ /* Compute the end of the selection & block in this dimension */ select_end = space->select.sel_info.hslab->diminfo.high_bounds[u]; block_end = (start[u] + block[u]) - 1; /* Check for overlap */ if (!H5S_RANGE_OVERLAP(space->select.sel_info.hslab->diminfo.opt[u].start, select_end, start[u], block_end)) { overlap = FALSE; break; } /* end if */ /* Find first span that is before or overlaps with start of block */ if (space->select.sel_info.hslab->diminfo.opt[u].start >= start[u]) { /* Calculate start & end of first span */ first_span_start = space->select.sel_info.hslab->diminfo.opt[u].start; first_span_end = (first_span_start + space->select.sel_info.hslab->diminfo.opt[u].block) - 1; /* Check if first span overlaps _end_ of block */ if (block_end >= first_span_start && block_end <= first_span_end) partial_first_span = TRUE; } /* end if */ else { hsize_t adj_start; /* Start coord, adjusted for hyperslab selection parameters */ /* Adjust start coord for selection's 'start' offset */ adj_start = start[u] - space->select.sel_info.hslab->diminfo.opt[u].start; /* Compute # of strides into the selection */ if (space->select.sel_info.hslab->diminfo.opt[u].count > 1) nstride = adj_start / space->select.sel_info.hslab->diminfo.opt[u].stride; else nstride = 0; /* Calculate start & end of first span */ first_span_start = space->select.sel_info.hslab->diminfo.opt[u].start + (nstride * space->select.sel_info.hslab->diminfo.opt[u].stride); first_span_end = (first_span_start + space->select.sel_info.hslab->diminfo.opt[u].block) - 1; /* Check if first span overlaps start of block */ if (first_span_start < start[u] && first_span_end >= start[u]) partial_first_span = TRUE; /* Advance first span to start higher than block's start, * if it's not partial. */ if (first_span_end < start[u]) { first_span_start += space->select.sel_info.hslab->diminfo.opt[u].stride; first_span_end += space->select.sel_info.hslab->diminfo.opt[u].stride; } /* end if */ } /* end else */ /* Find last span that is before or overlaps with end of block */ if (select_end < block_end) { /* Calculate start & end of last span */ last_span_start = (select_end - space->select.sel_info.hslab->diminfo.opt[u].block) + 1; last_span_end = select_end; /* Check if last span overlaps _start_ of block */ if (start[u] >= last_span_start && start[u] <= last_span_end) partial_last_span = TRUE; } /* end if */ else { hsize_t adj_end; /* End coord, adjusted for hyperslab selection parameters */ /* Adjust end coord for selection's 'start' offset */ adj_end = block_end - space->select.sel_info.hslab->diminfo.opt[u].start; /* Compute # of strides into the selection */ if (space->select.sel_info.hslab->diminfo.opt[u].count > 1) nstride = adj_end / space->select.sel_info.hslab->diminfo.opt[u].stride; else nstride = 0; /* Calculate start & end of last span */ last_span_start = space->select.sel_info.hslab->diminfo.opt[u].start + (nstride * space->select.sel_info.hslab->diminfo.opt[u].stride); last_span_end = (last_span_start + space->select.sel_info.hslab->diminfo.opt[u].block) - 1; /* Check if last span overlaps end of block */ if (block_end >= last_span_start && block_end <= last_span_end) partial_last_span = TRUE; } /* end else */ /* Check if no spans are inside block */ /* (Can happen when block falls in "gap" between spans) */ if (last_span_end < start[u]) { overlap = FALSE; break; } /* end if */ /* Sanity check */ HDassert(first_span_start <= last_span_start); /* Compute new start / count / block values */ new_start[u] = first_span_start; if (last_span_start != first_span_start) new_count[u] = ((last_span_start - first_span_start) / space->select.sel_info.hslab->diminfo.opt[u].stride) + 1; else new_count[u] = 1; new_block[u] = space->select.sel_info.hslab->diminfo.opt[u].block; /* Keep same stride */ stride[u] = space->select.sel_info.hslab->diminfo.opt[u].stride; } /* end for */ /* Check for overlap of selection & block */ if (overlap) { /* Set selection to regular hyperslab */ if (H5S__set_regular_hyperslab(space, new_start, stride, new_count, new_block, stride, new_count, new_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't set regular hyperslab selection") /* If there's a partial first or last span, have to 'AND' against selection */ if (partial_first_span || partial_last_span) { /* Generate span tree for regular selection */ if (H5S__hyper_generate_spans(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "dataspace does not have span tree") /* 'AND' against block */ if (H5S__generate_hyperslab(space, H5S_SELECT_AND, start, H5S_hyper_ones_g, H5S_hyper_ones_g, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't generate hyperslabs") } /* end if */ } /* end if */ else { /* Selection & block don't overlap, set to "none" selection */ if (H5S_select_none(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") } /* end else */ } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_regular_and_single_block() */ /*------------------------------------------------------------------------- * Function: H5S_select_hyperslab * * Purpose: Internal version of H5Sselect_hyperslab(). * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * Wednesday, January 10, 2001 * *------------------------------------------------------------------------- */ herr_t H5S_select_hyperslab(H5S_t *space, H5S_seloper_t op, const hsize_t start[], const hsize_t *stride, const hsize_t count[], const hsize_t *block) { hsize_t int_stride[H5S_MAX_RANK]; /* Internal storage for stride information */ hsize_t int_count[H5S_MAX_RANK]; /* Internal storage for count information */ hsize_t int_block[H5S_MAX_RANK]; /* Internal storage for block information */ const hsize_t *opt_stride; /* Optimized stride information */ const hsize_t *opt_count; /* Optimized count information */ const hsize_t *opt_block; /* Optimized block information */ int unlim_dim = -1; /* Unlimited dimension in selection, of -1 if none */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Check args */ HDassert(space); HDassert(start); HDassert(count); HDassert(op > H5S_SELECT_NOOP && op < H5S_SELECT_INVALID); /* Point to the correct stride values */ if (stride == NULL) stride = H5S_hyper_ones_g; /* Point to the correct block values */ if (block == NULL) block = H5S_hyper_ones_g; /* Check new selection */ for (u = 0; u < space->extent.rank; u++) { /* Check for overlapping hyperslab blocks in new selection. */ if (count[u] > 1 && stride[u] < block[u]) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "hyperslab blocks overlap") /* Detect zero-sized hyperslabs in new selection */ if (count[u] == 0 || block[u] == 0) { switch (op) { case H5S_SELECT_SET: /* Select "set" operation */ case H5S_SELECT_AND: /* Binary "and" operation for hyperslabs */ case H5S_SELECT_NOTA: /* Binary "B not A" operation for hyperslabs */ /* Convert to "none" selection */ if (H5S_select_none(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") HGOTO_DONE(SUCCEED); case H5S_SELECT_OR: /* Binary "or" operation for hyperslabs */ case H5S_SELECT_XOR: /* Binary "xor" operation for hyperslabs */ case H5S_SELECT_NOTB: /* Binary "A not B" operation for hyperslabs */ HGOTO_DONE(SUCCEED); /* Selection stays same */ case H5S_SELECT_NOOP: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ } /* end if */ /* Check for unlimited dimension */ if ((count[u] == H5S_UNLIMITED) || (block[u] == H5S_UNLIMITED)) { if (unlim_dim >= 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "cannot have more than one unlimited dimension in selection") else { if (count[u] == block[u]) /* Both are H5S_UNLIMITED */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "count and block cannot both be unlimited") unlim_dim = (int)u; } /* end else */ } /* end if */ } /* end for */ /* Optimize hyperslab parameters to merge contiguous blocks, etc. */ if (stride == H5S_hyper_ones_g && block == H5S_hyper_ones_g) { /* Point to existing arrays */ opt_stride = H5S_hyper_ones_g; opt_count = H5S_hyper_ones_g; opt_block = count; } /* end if */ else { /* Point to local arrays */ opt_stride = int_stride; opt_count = int_count; opt_block = int_block; for (u = 0; u < space->extent.rank; u++) { /* contiguous hyperslabs have the block size equal to the stride */ if ((stride[u] == block[u]) && (count[u] != H5S_UNLIMITED)) { int_count[u] = 1; int_stride[u] = 1; if (block[u] == 1) int_block[u] = count[u]; else int_block[u] = block[u] * count[u]; } /* end if */ else { if (count[u] == 1) int_stride[u] = 1; else { HDassert((stride[u] > block[u]) || ((stride[u] == block[u]) && (count[u] == H5S_UNLIMITED))); int_stride[u] = stride[u]; } /* end else */ int_count[u] = count[u]; int_block[u] = block[u]; } /* end else */ } /* end for */ } /* end else */ /* Check for operating on unlimited selection */ if ((H5S_GET_SELECT_TYPE(space) == H5S_SEL_HYPERSLABS) && (space->select.sel_info.hslab->unlim_dim >= 0) && (op != H5S_SELECT_SET)) { /* Check for invalid operation */ if (unlim_dim >= 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "cannot modify unlimited selection with another unlimited selection") if (!((op == H5S_SELECT_AND) || (op == H5S_SELECT_NOTA))) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unsupported operation on unlimited selection") HDassert(space->select.sel_info.hslab->diminfo_valid); /* Clip unlimited selection to include new selection */ if (H5S_hyper_clip_unlim(space, start[space->select.sel_info.hslab->unlim_dim] + ((opt_count[space->select.sel_info.hslab->unlim_dim] - (hsize_t)1) * opt_stride[space->select.sel_info.hslab->unlim_dim]) + opt_block[space->select.sel_info.hslab->unlim_dim]) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "failed to clip unlimited selection") /* If an empty space was returned it must be "none" */ HDassert((space->select.num_elem > (hsize_t)0) || (space->select.type->type == H5S_SEL_NONE)); } /* end if */ /* Fixup operation for non-hyperslab selections */ switch (H5S_GET_SELECT_TYPE(space)) { case H5S_SEL_NONE: /* No elements selected in dataspace */ switch (op) { case H5S_SELECT_SET: /* Select "set" operation */ /* Change "none" selection to hyperslab selection */ break; case H5S_SELECT_OR: /* Binary "or" operation for hyperslabs */ case H5S_SELECT_XOR: /* Binary "xor" operation for hyperslabs */ case H5S_SELECT_NOTA: /* Binary "B not A" operation for hyperslabs */ op = H5S_SELECT_SET; /* Maps to "set" operation when applied to "none" selection */ break; case H5S_SELECT_AND: /* Binary "and" operation for hyperslabs */ case H5S_SELECT_NOTB: /* Binary "A not B" operation for hyperslabs */ HGOTO_DONE(SUCCEED); /* Selection stays "none" */ case H5S_SELECT_NOOP: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ break; case H5S_SEL_ALL: /* All elements selected in dataspace */ switch (op) { case H5S_SELECT_SET: /* Select "set" operation */ /* Change "all" selection to hyperslab selection */ break; case H5S_SELECT_OR: /* Binary "or" operation for hyperslabs */ HGOTO_DONE(SUCCEED); /* Selection stays "all" */ case H5S_SELECT_AND: /* Binary "and" operation for hyperslabs */ op = H5S_SELECT_SET; /* Maps to "set" operation when applied to "none" selection */ break; case H5S_SELECT_XOR: /* Binary "xor" operation for hyperslabs */ case H5S_SELECT_NOTB: /* Binary "A not B" operation for hyperslabs */ /* Convert current "all" selection to "real" hyperslab selection */ /* Then allow operation to proceed */ { const hsize_t *tmp_start; /* Temporary start information */ const hsize_t *tmp_stride; /* Temporary stride information */ const hsize_t *tmp_count; /* Temporary count information */ const hsize_t *tmp_block; /* Temporary block information */ /* Set up temporary information for the dimensions */ tmp_start = H5S_hyper_zeros_g; tmp_stride = tmp_count = H5S_hyper_ones_g; tmp_block = space->extent.size; /* Convert to hyperslab selection */ if (H5S_select_hyperslab(space, H5S_SELECT_SET, tmp_start, tmp_stride, tmp_count, tmp_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't convert selection") } /* end case */ break; case H5S_SELECT_NOTA: /* Binary "B not A" operation for hyperslabs */ /* Convert to "none" selection */ if (H5S_select_none(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") HGOTO_DONE(SUCCEED); case H5S_SELECT_NOOP: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ break; case H5S_SEL_HYPERSLABS: /* Hyperslab operation on hyperslab selection, OK */ break; case H5S_SEL_POINTS: /* Can't combine hyperslab operations and point selections currently */ if (op == H5S_SELECT_SET) /* Allow only "set" operation to proceed */ break; /* FALLTHROUGH (to error) */ H5_ATTR_FALLTHROUGH case H5S_SEL_ERROR: case H5S_SEL_N: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ if (op == H5S_SELECT_SET) { /* Set selection to regular hyperslab */ if (H5S__set_regular_hyperslab(space, start, stride, count, block, opt_stride, opt_count, opt_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't set regular hyperslab selection") } /* end if */ else if (op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA) { hbool_t single_block; /* Whether the selection is a single block */ /* Sanity check */ HDassert(H5S_GET_SELECT_TYPE(space) == H5S_SEL_HYPERSLABS); /* Handle unlimited selections */ if (unlim_dim >= 0) { hsize_t bounds_start[H5S_MAX_RANK]; hsize_t bounds_end[H5S_MAX_RANK]; hsize_t tmp_count = opt_count[unlim_dim]; hsize_t tmp_block = opt_block[unlim_dim]; /* Check for invalid operation */ if (space->select.sel_info.hslab->unlim_dim >= 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "cannot modify unlimited selection with another unlimited selection") if (!((op == H5S_SELECT_AND) || (op == H5S_SELECT_NOTB))) HGOTO_ERROR(H5E_DATASPACE, H5E_UNSUPPORTED, FAIL, "unsupported operation with unlimited selection") /* Get bounds of existing selection */ if (H5S__hyper_bounds(space, bounds_start, bounds_end) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTGET, FAIL, "can't get selection bounds") /* Patch count and block to remove unlimited and include the * existing selection. */ H5S__hyper_get_clip_diminfo(start[unlim_dim], opt_stride[unlim_dim], &tmp_count, &tmp_block, bounds_end[unlim_dim] + (hsize_t)1); HDassert((tmp_count == 1) || (opt_count != H5S_hyper_ones_g)); HDassert((tmp_block == 1) || (opt_block != H5S_hyper_ones_g)); if (opt_count != H5S_hyper_ones_g) { HDassert(opt_count == int_count); int_count[unlim_dim] = tmp_count; } /* end if */ if (opt_block != H5S_hyper_ones_g) { HDassert(opt_block == int_block); int_block[unlim_dim] = tmp_block; } /* end if */ } /* end if */ /* Check for a single block selected */ single_block = TRUE; for (u = 0; u < space->extent.rank; u++) if (1 != opt_count[u]) { single_block = FALSE; break; } /* end if */ /* Check for single block "AND" operation on a regular hyperslab, which * is used for constructing chunk maps and can be optimized for. */ if (H5S_SELECT_AND == op && single_block && space->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { if (H5S__hyper_regular_and_single_block(space, start, opt_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTOPERATE, FAIL, "can't 'AND' single block against regular hyperslab") } /* end if */ else { /* Check if there's no hyperslab span information currently */ if (NULL == space->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "dataspace does not have span tree") /* Set selection type */ space->select.type = H5S_sel_hyper; /* Add in the new hyperslab information */ if (H5S__generate_hyperslab(space, op, start, opt_stride, opt_count, opt_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't generate hyperslabs") } /* end else */ } /* end if */ else HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_select_hyperslab() */ /*-------------------------------------------------------------------------- NAME H5Sselect_hyperslab PURPOSE Specify a hyperslab to combine with the current hyperslab selection USAGE herr_t H5Sselect_hyperslab(dsid, op, start, stride, count, block) hid_t dsid; IN: Dataspace ID of selection to modify H5S_seloper_t op; IN: Operation to perform on current selection const hsize_t *start; IN: Offset of start of hyperslab const hsize_t *stride; IN: Hyperslab stride const hsize_t *count; IN: Number of blocks included in hyperslab const hsize_t *block; IN: Size of block in hyperslab RETURNS Non-negative on success/Negative on failure DESCRIPTION Combines a hyperslab selection with the current selection for a dataspace. If the current selection is not a hyperslab, it is freed and the hyperslab parameters passed in are combined with the H5S_SEL_ALL hyperslab (ie. a selection composing the entire current extent). If STRIDE or BLOCK is NULL, they are assumed to be set to all '1'. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5Sselect_hyperslab(hid_t space_id, H5S_seloper_t op, const hsize_t start[], const hsize_t stride[], const hsize_t count[], const hsize_t block[]) { H5S_t *space; /* Dataspace to modify selection of */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE6("e", "iSs*h*h*h*h", space_id, op, start, stride, count, block); /* Check args */ if (NULL == (space = (H5S_t *)H5I_object_verify(space_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (H5S_SCALAR == H5S_GET_EXTENT_TYPE(space)) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "hyperslab doesn't support H5S_SCALAR space") if (H5S_NULL == H5S_GET_EXTENT_TYPE(space)) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "hyperslab doesn't support H5S_NULL space") if (start == NULL || count == NULL) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "hyperslab not specified") if (!(op > H5S_SELECT_NOOP && op < H5S_SELECT_INVALID)) HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") if (stride != NULL) { unsigned u; /* Local index variable */ /* Check for 0-sized strides */ for (u = 0; u < space->extent.rank; u++) if (stride[u] == 0) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "invalid stride==0 value") } /* end if */ if (H5S_select_hyperslab(space, op, start, stride, count, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to set hyperslab selection") done: FUNC_LEAVE_API(ret_value) } /* end H5Sselect_hyperslab() */ /*-------------------------------------------------------------------------- NAME H5S_combine_hyperslab PURPOSE Specify a hyperslab to combine with the current hyperslab selection, and store the result in the new hyperslab selection. USAGE herr_t H5S_combine_hyperslab(old_space, op, start, stride, count, block, new_space) H5S_t *old_space; IN: The old space the selection is performed on H5S_seloper_t op; IN: Operation to perform on current selection const hsize_t start[]; IN: Offset of start of hyperslab const hsize_t *stride; IN: Hyperslab stride const hsize_t count[]; IN: Number of blocks included in hyperslab const hsize_t *block; IN: Size of block in hyperslab H5S_t **new_space; OUT: The new dataspace to store the selection result RETURNS Non-negative on success/Negative on failure DESCRIPTION Combines a hyperslab selection with the current selection for a dataspace. If STRIDE or BLOCK is NULL, they are assumed to be set to all '1'. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS In some cases, copying the whole span tree from old_space to new_space can be avoided. Deal with such cases directly, otherwise this function is equivalent to: 1. Copy the whole span tree from old_space into new_space 2. Call H5S_select_hyperslab with the new_space. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5S_combine_hyperslab(const H5S_t *old_space, H5S_seloper_t op, const hsize_t start[], const hsize_t *stride, const hsize_t count[], const hsize_t *block, H5S_t **new_space) { unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Check args */ HDassert(old_space); HDassert(start); HDassert(count); HDassert(op >= H5S_SELECT_SET && op <= H5S_SELECT_NOTA); HDassert(new_space); HDassert(*new_space == NULL); /* Point to the correct stride values */ if (stride == NULL) stride = H5S_hyper_ones_g; /* Point to the correct block values */ if (block == NULL) block = H5S_hyper_ones_g; /* Check new selection. */ for (u = 0; u < old_space->extent.rank; u++) { /* Check for overlapping hyperslab blocks in new selection. */ if (count[u] > 1 && stride[u] < block[u]) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "hyperslab blocks overlap") /* Detect zero-sized hyperslabs in new selection */ if (count[u] == 0 || block[u] == 0) { switch (op) { case H5S_SELECT_AND: /* Binary "and" operation for hyperslabs */ case H5S_SELECT_NOTA: /* Binary "B not A" operation for hyperslabs */ /* Convert to "none" selection */ /* Copy the first dataspace without sharing the list of spans */ if (NULL == ((*new_space) = H5S_copy(old_space, TRUE, TRUE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to copy dataspace") if (H5S_select_none((*new_space)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") HGOTO_DONE(SUCCEED); case H5S_SELECT_OR: /* Binary "or" operation for hyperslabs */ case H5S_SELECT_XOR: /* Binary "xor" operation for hyperslabs */ case H5S_SELECT_NOTB: /* Binary "A not B" operation for hyperslabs */ /* Copy the first dataspace with sharing the list of spans */ if (NULL == ((*new_space) = H5S_copy(old_space, FALSE, TRUE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to copy dataspace") HGOTO_DONE(SUCCEED); /* Selection stays same */ case H5S_SELECT_NOOP: case H5S_SELECT_SET: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ } /* end if */ } /* end for */ if (H5S_GET_SELECT_TYPE(old_space) == H5S_SEL_HYPERSLABS) { hsize_t *old_low_bounds; /* Pointer to old space's low & high bounds */ hsize_t *old_high_bounds; hsize_t new_low_bounds[H5S_MAX_RANK]; /* New space's low & high bounds */ hsize_t new_high_bounds[H5S_MAX_RANK]; hbool_t overlapped = FALSE; /* Set up old space's low & high bounds */ if (old_space->select.sel_info.hslab->span_lst) { old_low_bounds = old_space->select.sel_info.hslab->span_lst->low_bounds; old_high_bounds = old_space->select.sel_info.hslab->span_lst->high_bounds; } /* end if */ else { old_low_bounds = old_space->select.sel_info.hslab->diminfo.low_bounds; old_high_bounds = old_space->select.sel_info.hslab->diminfo.high_bounds; } /* end else */ /* Generate bounding box for hyperslab parameters */ for (u = 0; u < old_space->extent.rank; u++) { new_low_bounds[u] = start[u]; new_high_bounds[u] = start[u] + stride[u] * (count[u] - 1) + (block[u] - 1); } /* end for */ /* Check bound box of both spaces to see if they overlap */ if (H5S_RANGE_OVERLAP(old_low_bounds[0], old_high_bounds[0], new_low_bounds[0], new_high_bounds[0])) overlapped = TRUE; /* Non-overlapping situations can be handled in special ways */ if (!overlapped) { H5S_hyper_span_info_t *new_spans = NULL; H5S_hyper_dim_t new_hyper_diminfo[H5S_MAX_RANK]; if (NULL == ((*new_space) = H5S_copy(old_space, TRUE, TRUE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy dataspace") if (NULL != (*new_space)->select.sel_info.hslab->span_lst) { old_space->select.sel_info.hslab->span_lst->count--; (*new_space)->select.sel_info.hslab->span_lst = NULL; } /* end if */ /* Generate hyperslab info for new space */ switch (op) { case H5S_SELECT_OR: case H5S_SELECT_XOR: /* Add the new space to the space */ if (NULL == (new_spans = H5S__hyper_make_spans(old_space->extent.rank, start, stride, count, block))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't create hyperslab information") if (NULL != old_space->select.sel_info.hslab->span_lst) (*new_space)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span( old_space->select.sel_info.hslab->span_lst, old_space->extent.rank); if (H5S__hyper_add_disjoint_spans(*new_space, new_spans) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't append hyperslabs") /* Build diminfo struct */ for (u = 0; u < (*new_space)->extent.rank; u++) { new_hyper_diminfo[u].start = start[u]; new_hyper_diminfo[u].stride = stride[u]; new_hyper_diminfo[u].count = count[u]; new_hyper_diminfo[u].block = block[u]; } /* end for */ /* Update space's dim info */ if (H5S__hyper_update_diminfo(*new_space, op, new_hyper_diminfo) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOUNT, FAIL, "can't update hyperslab info") break; case H5S_SELECT_AND: if (H5S_select_none((*new_space)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") break; case H5S_SELECT_NOTB: if (NULL != old_space->select.sel_info.hslab->span_lst) { if (NULL == ((*new_space)->select.sel_info.hslab->span_lst = H5S__hyper_copy_span( old_space->select.sel_info.hslab->span_lst, old_space->extent.rank))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "unable to copy dataspace") } /* end if */ else { if (H5S_select_none((*new_space)) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't convert selection") } /* end else */ break; case H5S_SELECT_NOTA: if (H5S__set_regular_hyperslab(*new_space, start, stride, count, block, stride, count, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSET, FAIL, "can't set regular selection") break; case H5S_SELECT_NOOP: case H5S_SELECT_SET: case H5S_SELECT_APPEND: case H5S_SELECT_PREPEND: case H5S_SELECT_INVALID: default: HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") } /* end switch */ HGOTO_DONE(SUCCEED); } /* end if(!overlapped) */ } /* end if the selection of old space is H5S_SEL_HYPERSLABS */ /* Copy the first dataspace with sharing the list of spans */ if (NULL == ((*new_space) = H5S_copy(old_space, TRUE, TRUE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to copy dataspace") /* Note: a little overhead in calling the function as some conditions are checked again */ if (H5S_select_hyperslab(*new_space, op, start, stride, count, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to set hyperslab selection") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_combine_hyperslab() */ /*------------------------------------------------------------------------- * Function: H5S__fill_in_select * * Purpose: Combines two hyperslabs with an operation, putting the * result into a third hyperslab selection * * Return: Non-negative on success/negative on failure * * Programmer: Chao Mei * Tuesday, July 5, 2011 * *------------------------------------------------------------------------- */ static herr_t H5S__fill_in_select(H5S_t *space1, H5S_seloper_t op, H5S_t *space2, H5S_t **result) { hbool_t span2_owned; hbool_t updated_spans; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Sanity check */ HDassert(space1); HDassert(space2); HDassert(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA); HDassert(space1->extent.rank == space2->extent.rank); /* The result is either a to-be-created space or an empty one */ HDassert(NULL == *result || *result == space1); HDassert(space1->select.sel_info.hslab->span_lst); HDassert(space2->select.sel_info.hslab->span_lst); /* Note: the offset of space2 is not considered here for bounding box */ if (H5S__fill_in_new_space(space1, op, space2->select.sel_info.hslab->span_lst, FALSE, &span2_owned, &updated_spans, result) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTSELECT, FAIL, "can't create the specified selection") /* Update diminfo if space2's diminfo was valid, otherwise just mark it as * invalid if the spans were updated */ HDassert(result); if (updated_spans) { if (space2->select.sel_info.hslab->diminfo_valid == H5S_DIMINFO_VALID_YES) { if (H5S__hyper_update_diminfo(*result, op, space2->select.sel_info.hslab->diminfo.opt) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOUNT, FAIL, "can't update hyperslab info") } /* end if */ else (*result)->select.sel_info.hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; } /* end if */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__fill_in_select() */ /*-------------------------------------------------------------------------- NAME H5Scombine_hyperslab PURPOSE Specify a hyperslab to combine with the current hyperslab selection and return a new dataspace with the combined selection as the selection in the new dataspace. USAGE hid_t H5Scombine_hyperslab(dsid, op, start, stride, count, block) hid_t dsid; IN: Dataspace ID of selection to use H5S_seloper_t op; IN: Operation to perform on current selection const hsize_t *start; IN: Offset of start of hyperslab const hsize_t *stride; IN: Hyperslab stride const hsize_t *count; IN: Number of blocks included in hyperslab const hsize_t *block; IN: Size of block in hyperslab RETURNS Dataspace ID on success / H5I_INVALID_HID on failure DESCRIPTION Combines a hyperslab selection with the current selection for a dataspace, creating a new dataspace to return the generated selection. If the current selection is not a hyperslab, it is freed and the hyperslab parameters passed in are combined with the H5S_SEL_ALL hyperslab (ie. a selection composing the entire current extent). If STRIDE or BLOCK is NULL, they are assumed to be set to all '1'. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hid_t H5Scombine_hyperslab(hid_t space_id, H5S_seloper_t op, const hsize_t start[], const hsize_t stride[], const hsize_t count[], const hsize_t block[]) { H5S_t *space; /* Dataspace to modify selection of */ H5S_t *new_space = NULL; /* New dataspace created */ hid_t ret_value; /* Return value */ FUNC_ENTER_API(H5I_INVALID_HID) H5TRACE6("i", "iSs*h*h*h*h", space_id, op, start, stride, count, block); /* Check args */ if (NULL == (space = (H5S_t *)H5I_object_verify(space_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, H5I_INVALID_HID, "not a dataspace") if (start == NULL || count == NULL) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, H5I_INVALID_HID, "hyperslab not specified") if (!(op >= H5S_SELECT_SET && op <= H5S_SELECT_NOTA)) HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, H5I_INVALID_HID, "invalid selection operation") /* Generate new space, with combination of selections */ if (H5S_combine_hyperslab(space, op, start, stride, count, block, &new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, H5I_INVALID_HID, "unable to set hyperslab selection") /* Register */ if ((ret_value = H5I_register(H5I_DATASPACE, new_space, TRUE)) < 0) HGOTO_ERROR(H5E_ID, H5E_CANTREGISTER, H5I_INVALID_HID, "unable to register dataspace ID") done: if (ret_value < 0 && new_space) H5S_close(new_space); FUNC_LEAVE_API(ret_value) } /* end H5Scombine_hyperslab() */ /*------------------------------------------------------------------------- * Function: H5S__combine_select * * Purpose: Internal version of H5Scombine_select(). * * Return: New dataspace on success/NULL on failure * * Programmer: Quincey Koziol * Tuesday, October 30, 2001 * *------------------------------------------------------------------------- */ static H5S_t * H5S__combine_select(H5S_t *space1, H5S_seloper_t op, H5S_t *space2) { H5S_t *new_space = NULL; /* New dataspace generated */ H5S_t *ret_value = NULL; /* Return value */ FUNC_ENTER_STATIC /* Check args */ HDassert(space1); HDassert(space2); HDassert(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA); /* Check if space1 selections has span trees */ if (NULL == space1->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans(space1) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, NULL, "dataspace does not have span tree") if (NULL == space2->select.sel_info.hslab->span_lst) { hsize_t tmp_start[H5S_MAX_RANK]; hsize_t tmp_stride[H5S_MAX_RANK]; hsize_t tmp_count[H5S_MAX_RANK]; hsize_t tmp_block[H5S_MAX_RANK]; unsigned u; for (u = 0; u < space2->extent.rank; u++) { tmp_start[u] = space2->select.sel_info.hslab->diminfo.opt[u].start; tmp_stride[u] = space2->select.sel_info.hslab->diminfo.opt[u].stride; tmp_count[u] = space2->select.sel_info.hslab->diminfo.opt[u].count; tmp_block[u] = space2->select.sel_info.hslab->diminfo.opt[u].block; } /* end for */ /* Combine hyperslab selection with regular selection directly */ if (H5S_combine_hyperslab(space1, op, tmp_start, tmp_stride, tmp_count, tmp_block, &new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, NULL, "unable to set hyperslab selection") } /* end if */ else { /* Combine new_space (a copy of space 1) & space2, with the result in new_space */ if (H5S__fill_in_select(space1, op, space2, &new_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, NULL, "can't clip hyperslab information") } /* end else */ /* Set unlim_dim */ new_space->select.sel_info.hslab->unlim_dim = -1; /* Set return value */ ret_value = new_space; done: if (ret_value == NULL && new_space) H5S_close(new_space); FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__combine_select() */ /*-------------------------------------------------------------------------- NAME H5Scombine_select PURPOSE Combine two hyperslab selections with an operation, returning a dataspace with the resulting selection. USAGE hid_t H5Scombine_select(space1, op, space2) hid_t space1; IN: First Dataspace ID H5S_seloper_t op; IN: Selection operation hid_t space2; IN: Second Dataspace ID RETURNS Dataspace ID on success / H5I_INVALID_HID on failure DESCRIPTION Combine two existing hyperslab selections with an operation, returning a new dataspace with the resulting selection. The dataspace extent from space1 is copied for the dataspace extent of the newly created dataspace. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hid_t H5Scombine_select(hid_t space1_id, H5S_seloper_t op, hid_t space2_id) { H5S_t *space1; /* First Dataspace */ H5S_t *space2; /* Second Dataspace */ H5S_t *new_space = NULL; /* New Dataspace */ hid_t ret_value; /* Return value */ FUNC_ENTER_API(H5I_INVALID_HID) H5TRACE3("i", "iSsi", space1_id, op, space2_id); /* Check args */ if (NULL == (space1 = (H5S_t *)H5I_object_verify(space1_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, H5I_INVALID_HID, "not a dataspace") if (NULL == (space2 = (H5S_t *)H5I_object_verify(space2_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, H5I_INVALID_HID, "not a dataspace") if (!(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA)) HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, H5I_INVALID_HID, "invalid selection operation") /* Check that both dataspaces have the same rank */ if (space1->extent.rank != space2->extent.rank) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, H5I_INVALID_HID, "dataspaces not same rank") /* Note: currently, the offset of each dataspace is ignored */ #if 0 /* Check that both dataspaces have the same offset */ /* Same note as in H5Smodify_select */ for(u=0; u<space1->extent.rank; u++) { if(space1->select.offset[u] != space2->select.offset[u]) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, H5I_INVALID_HID, "dataspaces not same offset") } /* end for */ #endif /* Check that both dataspaces have hyperslab selections */ if (H5S_GET_SELECT_TYPE(space1) != H5S_SEL_HYPERSLABS || H5S_GET_SELECT_TYPE(space2) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, H5I_INVALID_HID, "dataspaces don't have hyperslab selections") /* Go combine the dataspaces */ if (NULL == (new_space = H5S__combine_select(space1, op, space2))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, H5I_INVALID_HID, "unable to create hyperslab selection") /* Register */ if ((ret_value = H5I_register(H5I_DATASPACE, new_space, TRUE)) < 0) HGOTO_ERROR(H5E_ID, H5E_CANTREGISTER, H5I_INVALID_HID, "unable to register dataspace ID") done: if (ret_value < 0 && new_space) H5S_close(new_space); FUNC_LEAVE_API(ret_value) } /* end H5Scombine_select() */ /*------------------------------------------------------------------------- * Function: H5S__modify_select * * Purpose: Internal version of H5Smodify_select(). * * Return: New dataspace on success/NULL on failure * * Programmer: Quincey Koziol * Tuesday, October 30, 2001 * *------------------------------------------------------------------------- */ herr_t H5S__modify_select(H5S_t *space1, H5S_seloper_t op, H5S_t *space2) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_PACKAGE /* Check args */ HDassert(space1); HDassert(space2); HDassert(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA); /* Check that the space selections both have span trees */ if (NULL == space1->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans(space1) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "dataspace does not have span tree") /* Set unlim_dim */ space1->select.sel_info.hslab->unlim_dim = -1; if (NULL == space2->select.sel_info.hslab->span_lst) { hsize_t tmp_start[H5S_MAX_RANK]; hsize_t tmp_stride[H5S_MAX_RANK]; hsize_t tmp_count[H5S_MAX_RANK]; hsize_t tmp_block[H5S_MAX_RANK]; unsigned u; for (u = 0; u < space2->extent.rank; u++) { tmp_start[u] = space2->select.sel_info.hslab->diminfo.opt[u].start; tmp_stride[u] = space2->select.sel_info.hslab->diminfo.opt[u].stride; tmp_count[u] = space2->select.sel_info.hslab->diminfo.opt[u].count; tmp_block[u] = space2->select.sel_info.hslab->diminfo.opt[u].block; } /* end for */ /* Call H5S_select_hyperslab directly */ if (H5S_select_hyperslab(space1, op, tmp_start, tmp_stride, tmp_count, tmp_block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to set hyperslab selection") } /* end if */ else /* Combine spans from space1 & spans from space2, with the result in space1 */ if (H5S__fill_in_select(space1, op, space2, &space1) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCLIP, FAIL, "can't perform operation on two selections") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__modify_select() */ /*-------------------------------------------------------------------------- NAME H5Smodify_select PURPOSE Refine a hyperslab selection with an operation using a second hyperslab to modify it USAGE herr_t H5Smodify_select(space1, op, space2) hid_t space1; IN/OUT: First Dataspace ID H5S_seloper_t op; IN: Selection operation hid_t space2; IN: Second Dataspace ID RETURNS Non-negative on success/Negative on failure DESCRIPTION Refine an existing hyperslab selection with an operation, using a second hyperslab. The first selection is modified to contain the result of space1 operated on by space2. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5Smodify_select(hid_t space1_id, H5S_seloper_t op, hid_t space2_id) { H5S_t *space1; /* First Dataspace */ H5S_t *space2; /* Second Dataspace */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE3("e", "iSsi", space1_id, op, space2_id); /* Check args */ if (NULL == (space1 = (H5S_t *)H5I_object_verify(space1_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (NULL == (space2 = (H5S_t *)H5I_object_verify(space2_id, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (!(op >= H5S_SELECT_OR && op <= H5S_SELECT_NOTA)) HGOTO_ERROR(H5E_ARGS, H5E_UNSUPPORTED, FAIL, "invalid selection operation") /* Check that both dataspaces have the same rank */ if (space1->extent.rank != space2->extent.rank) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "dataspaces not same rank") /* Check that both dataspaces have the same offset */ /** Note that this is a tricky part of this function. It's * possible that two dataspaces have different "offset". If the * space2 has smaller offset value than that of space1 in a * dimension, then the span elements of this dimension in * space2 could have negative "low" and "high" values relative * to the offset in space1. In other words, if the bounds of * span elements in space2 are adjusted relative to the offset * in space1, then every span element's bound is computed as * "origin_bound+offset2-offset1". Therefore, if offset2 (the * offset of space2) is smaller, then * "origin_bound+offset2-offset1" could be negative which is * not allowed by the bound type declaration as hsize_t! * As a result, if the op is an OR selection, then the final * result may contain span elements that have negative bound! * So right now, the difference in the offset is totally * ignored!! */ #if 0 for(u=0; u<space1->extent.rank; u++) { if(space1->select.offset[u] != space2->select.offset[u]) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "dataspaces not same offset") } /* end for */ #endif /* Check that both dataspaces have hyperslab selections */ if (H5S_GET_SELECT_TYPE(space1) != H5S_SEL_HYPERSLABS || H5S_GET_SELECT_TYPE(space2) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADVALUE, FAIL, "dataspaces don't have hyperslab selections") /* Go refine the first selection */ if (H5S__modify_select(space1, op, space2) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to modify hyperslab selection") done: FUNC_LEAVE_API(ret_value) } /* end H5Smodify_select() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_proj_int_build_proj PURPOSE Secondary iteration routine for H5S__hyper_project_intersection USAGE herr_t H5S__hyper_proj_int_build_proj(udata) H5S_hyper_project_intersect_ud_t *udata; IN/OUT: Persistent shared data for iteration RETURNS Non-negative on success/Negative on failure. DESCRIPTION Takes the skip and nelem amounts listed in udata and converts them to span trees in the projected space, using the destination space. This is a non-recursive algorithm by necessity, it saves the current state of iteration in udata and resumes in the same location on subsequent calls. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_proj_int_build_proj(H5S_hyper_project_intersect_ud_t *udata) { H5S_hyper_span_info_t *copied_span_info = NULL; /* Temporary span info pointer */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC HDassert(udata->nelem > 0); /* * Skip over skipped elements */ if (udata->skip > 0) { /* Work upwards, finishing each span tree before moving up */ HDassert(udata->ds_span[udata->depth]); do { /* Check for lowest dimension */ if (udata->ds_span[udata->depth]->down) { if (udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high) { /* If we will run out of elements to skip in this span, * advance to the first not fully skipped span and break * out of this loop (start moving downwards) */ if (udata->skip < H5S__hyper_spans_nelem_helper(udata->ds_span[udata->depth]->down, 0, udata->op_gen) * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { udata->ds_low[udata->depth] += udata->skip / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; udata->skip %= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; break; } /* end if */ /* Skip over this entire span */ udata->skip -= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1); } /* end if */ } /* end if */ else { HDassert(udata->ds_rank - udata->depth == 1); /* If we will run out of elements to skip in this span, * skip the remainder of the skipped elements and break out */ HDassert(udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high); if (udata->skip < (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { udata->ds_low[udata->depth] += udata->skip; udata->skip = 0; break; } /* end if */ /* Skip over this entire span */ udata->skip -= udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1; } /* end else */ /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; if (udata->ds_span[udata->depth]) udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; else if (udata->depth > 0) { /* If present, append this span tree to the higher dimension's, * and release ownership of it */ if (udata->ps_span_info[udata->depth]) { if (H5S__hyper_append_span( &udata->ps_span_info[udata->depth - 1], udata->ds_rank - udata->depth + 1, udata->ds_low[udata->depth - 1], udata->ds_low[udata->depth - 1], udata->ps_span_info[udata->depth]) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(udata->ps_span_info[udata->depth]); udata->ps_span_info[udata->depth] = NULL; } /* end if */ /* Ran out of spans, move up one dimension */ udata->depth--; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth]++; } /* end if */ else HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "insufficient elements in destination selection") } while ((udata->skip > 0) || (udata->ds_low[udata->depth] > udata->ds_span[udata->depth]->high)); /* Work downwards until skip is 0 */ HDassert(udata->ds_span[udata->depth]); while (udata->skip > 0) { HDassert(udata->ds_span[udata->depth]->down); udata->depth++; udata->ds_span[udata->depth] = udata->ds_span[udata->depth - 1]->down->head; udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; if (udata->ds_span[udata->depth]->down) { do { /* If we will run out of elements to skip in this span, * advance to the first not fully skipped span and * continue down */ if (udata->skip < H5S__hyper_spans_nelem_helper(udata->ds_span[udata->depth]->down, 0, udata->op_gen) * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { udata->ds_low[udata->depth] += udata->skip / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; udata->skip %= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; break; } /* end if */ /* Skip over this entire span */ udata->skip -= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1); /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; } while (udata->skip > 0); } /* end if */ else { do { /* If we will run out of elements to skip in this span, * skip the remainder of the skipped elements */ if (udata->skip < (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { udata->ds_low[udata->depth] += udata->skip; udata->skip = 0; break; } /* end if */ /* Skip over this entire span */ udata->skip -= udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1; /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; } while (udata->skip > 0); } /* end else */ } /* end while */ } /* end if */ /* * Add requested number of elements to projected space */ /* Work upwards, adding all elements of each span tree until it can't fit * all elements */ HDassert(udata->ds_span[udata->depth]); do { /* Check for lowest dimension */ if (udata->ds_span[udata->depth]->down) { if (udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high) { /* If we will run out of elements to add in this span, add * any complete spans, advance to the first not fully added * span, and break out of this loop (start moving downwards) */ if (udata->nelem < H5S__hyper_spans_nelem_helper(udata->ds_span[udata->depth]->down, 0, udata->op_gen) * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { if (udata->nelem >= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) { if (udata->share_selection) { if (H5S__hyper_append_span( &udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + (udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) - 1, udata->ds_span[udata->depth]->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* If we're not sharing the destination space's * spans, we must copy it first (then release it * afterwards) */ if (NULL == (copied_span_info = H5S__hyper_copy_span_helper( udata->ds_span[udata->depth]->down, udata->ds_rank - udata->depth, 1, udata->op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "can't copy destination spans") if (H5S__hyper_append_span( &udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + (udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) - 1, copied_span_info) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(copied_span_info); copied_span_info = NULL; } /* end else */ udata->ds_low[udata->depth] += udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; udata->nelem %= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; } /* end if */ break; } /* end if */ /* Append span tree for entire span */ if (udata->share_selection) { if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, udata->ds_span[udata->depth]->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* If we're not sharing the destination space's * spans, we must copy it first (then release it * afterwards) */ if (NULL == (copied_span_info = H5S__hyper_copy_span_helper( udata->ds_span[udata->depth]->down, udata->ds_rank - udata->depth, 1, udata->op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "can't copy destination spans") if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, copied_span_info) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(copied_span_info); copied_span_info = NULL; } /* end else */ udata->nelem -= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1); } /* end if */ } /* end if */ else { HDassert(udata->ds_rank - udata->depth == 1); /* If we will run out of elements to add in this span, add the * remainder of the elements and break out */ HDassert(udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high); if (udata->nelem < (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], 1, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + udata->nelem - 1, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") udata->ds_low[udata->depth] += udata->nelem; udata->nelem = 0; break; } /* end if */ /* Append span tree for entire span */ if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], 1, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") udata->nelem -= udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1; } /* end else */ /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; if (udata->ds_span[udata->depth]) udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; else if (udata->depth > 0) { /* Append this span tree to the higher dimension's, and release * ownership of it */ HDassert(udata->ps_span_info[udata->depth]); if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth - 1], udata->ds_rank - udata->depth + 1, udata->ds_low[udata->depth - 1], udata->ds_low[udata->depth - 1], udata->ps_span_info[udata->depth]) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(udata->ps_span_info[udata->depth]); udata->ps_span_info[udata->depth] = NULL; /* Ran out of spans, move up one dimension */ udata->depth--; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth]++; } /* end if */ else { /* We have finished the entire destination span tree. If there are * still elements to add, issue an error. */ if (udata->nelem > 0) HGOTO_ERROR(H5E_DATASPACE, H5E_BADVALUE, FAIL, "insufficient elements in destination selection") break; } /* end else */ } while ((udata->nelem > 0) || (udata->ds_low[udata->depth] > udata->ds_span[udata->depth]->high)); /* Work downwards until nelem is 0 */ HDassert(udata->ds_span[udata->depth] || (udata->nelem == 0)); while (udata->nelem > 0) { HDassert(udata->ds_span[udata->depth]->down); udata->depth++; udata->ds_span[udata->depth] = udata->ds_span[udata->depth - 1]->down->head; udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; if (udata->ds_span[udata->depth]->down) { do { /* If we will run out of elements to add in this span, add * any complete spans, advance to the first not fully added * span and continue down */ HDassert(udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high); if (udata->nelem < H5S__hyper_spans_nelem_helper(udata->ds_span[udata->depth]->down, 0, udata->op_gen) * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { if (udata->nelem >= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) { if (udata->share_selection) { if (H5S__hyper_append_span( &udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + (udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) - 1, udata->ds_span[udata->depth]->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* If we're not sharing the destination space's * spans, we must copy it first (then release it * afterwards) */ if (NULL == (copied_span_info = H5S__hyper_copy_span_helper( udata->ds_span[udata->depth]->down, udata->ds_rank - udata->depth, 1, udata->op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "can't copy destination spans") if (H5S__hyper_append_span( &udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + (udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts) - 1, copied_span_info) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(copied_span_info); copied_span_info = NULL; } /* end else */ udata->ds_low[udata->depth] += udata->nelem / udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; udata->nelem %= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts; } /* end if */ break; } /* end if */ /* Append span tree for entire span */ if (udata->share_selection) { if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, udata->ds_span[udata->depth]->down) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") } /* end if */ else { /* If we're not sharing the destination space's * spans, we must copy it first (then release it * afterwards) */ if (NULL == (copied_span_info = H5S__hyper_copy_span_helper( udata->ds_span[udata->depth]->down, udata->ds_rank - udata->depth, 1, udata->op_gen))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, FAIL, "can't copy destination spans") if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], udata->ds_rank - udata->depth, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, copied_span_info) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(copied_span_info); copied_span_info = NULL; } /* end else */ udata->nelem -= udata->ds_span[udata->depth]->down->op_info[0].u.nelmts * (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1); /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; } while (udata->nelem > 0); } /* end if */ else { HDassert(udata->ds_rank - udata->depth == 1); do { /* If we will run out of elements to add in this span, add * the remainder of the elements and break out */ HDassert(udata->ds_low[udata->depth] <= udata->ds_span[udata->depth]->high); if (udata->nelem < (udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1)) { if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], 1, udata->ds_low[udata->depth], udata->ds_low[udata->depth] + udata->nelem - 1, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") udata->ds_low[udata->depth] += udata->nelem; udata->nelem = 0; break; } /* end if */ /* Append span tree for entire span */ if (H5S__hyper_append_span(&udata->ps_span_info[udata->depth], 1, udata->ds_low[udata->depth], udata->ds_span[udata->depth]->high, NULL) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") udata->nelem -= udata->ds_span[udata->depth]->high - udata->ds_low[udata->depth] + 1; /* Advance to next span */ udata->ds_span[udata->depth] = udata->ds_span[udata->depth]->next; HDassert(udata->ds_span[udata->depth]); udata->ds_low[udata->depth] = udata->ds_span[udata->depth]->low; } while (udata->nelem > 0); } /* end else */ } /* end while */ HDassert(udata->skip == 0); HDassert(udata->nelem == 0); /* Mark projected space as changed (for all ranks) */ udata->ps_clean_bitmap = 0; done: /* Cleanup on failure */ if (copied_span_info) { HDassert(ret_value < 0); H5S__hyper_free_span_info(copied_span_info); copied_span_info = NULL; } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_proj_int_build_proj() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_proj_int_iterate PURPOSE Main iteration routine for H5S__hyper_project_intersection USAGE herr_t H5S__hyper_proj_int_iterate(ss_span_info,sis_span_info,count,depth,udata) const H5S_hyper_span_info_t *ss_span_info; IN: Span tree for source selection const H5S_hyper_span_info_t *sis_span_info; IN: Span tree for source intersect selection hsize_t count; IN: Number of times to compute the intersection of ss_span_info and sis_span_info unsigned depth; IN: Depth of iteration (in terms of rank) H5S_hyper_project_intersect_ud_t *udata; IN/OUT: Persistent shared data for iteration RETURNS Non-negative on success/Negative on failure. DESCRIPTION Computes the intersection of ss_span_info and sis_span_info and projects it to the projected space (held in udata). It accomplishes this by iterating over both spaces and computing the number of elements to skip (in ss_span_info) and the number of elements to add (the intersection) in a sequential fashion (similar to run length encoding). As necessary, this function both recurses into lower dimensions and calls H5S__hyper_proj_int_build_proj to convert the skip/nelem pairs to the projected span tree. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static herr_t H5S__hyper_proj_int_iterate(const H5S_hyper_span_info_t *ss_span_info, const H5S_hyper_span_info_t *sis_span_info, hsize_t count, unsigned depth, H5S_hyper_project_intersect_ud_t *udata) { const H5S_hyper_span_t *ss_span; /* Current span in source space */ const H5S_hyper_span_t *sis_span; /* Current span in source intersect space */ hsize_t ss_low; /* Current low bounds of source span */ hsize_t sis_low; /* Current low bounds of source intersect span */ hsize_t high; /* High bounds of current intersection */ hsize_t low; /* Low bounds of current intersection */ hsize_t old_skip; /* Value of udata->skip before main loop */ hsize_t old_nelem; /* Value of udata->nelem before main loop */ hbool_t check_intersect; /* Whether to check for intersecting elements */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_STATIC /* Check for non-overlapping bounds */ check_intersect = TRUE; for (u = 0; u < (udata->ss_rank - depth); u++) if (!H5S_RANGE_OVERLAP(ss_span_info->low_bounds[u], ss_span_info->high_bounds[u], sis_span_info->low_bounds[u], sis_span_info->high_bounds[u])) { check_intersect = FALSE; break; } /* end if */ /* Only enter main loop if there's something to do */ if (check_intersect) { /* Set ps_clean_bitmap */ udata->ps_clean_bitmap |= (((uint32_t)1) << depth); /* Save old skip and nelem */ old_skip = udata->skip; old_nelem = udata->nelem; /* Intersect spaces once per count */ for (u = 0; u < count; u++) { ss_span = ss_span_info->head; sis_span = sis_span_info->head; HDassert(ss_span && sis_span); ss_low = ss_span->low; sis_low = sis_span->low; /* Main loop */ do { /* Check if spans overlap */ if (H5S_RANGE_OVERLAP(ss_low, ss_span->high, sis_low, sis_span->high)) { high = MIN(ss_span->high, sis_span->high); if (ss_span->down) { /* Add skipped elements if there's a pre-gap */ if (ss_low < sis_low) { low = sis_low; H5S_HYPER_PROJ_INT_ADD_SKIP( udata, H5S__hyper_spans_nelem_helper(ss_span->down, 0, udata->op_gen) * (sis_low - ss_low), FAIL); } /* end if */ else low = ss_low; /* Recurse into next dimension down */ if (H5S__hyper_proj_int_iterate(ss_span->down, sis_span->down, high - low + 1, depth + 1, udata) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOMPARE, FAIL, "can't iterate over source selections") } /* end if */ else { HDassert(depth == udata->ss_rank - 1); /* Add skipped elements if there's a pre-gap */ if (ss_low < sis_low) { low = sis_low; H5S_HYPER_PROJ_INT_ADD_SKIP(udata, sis_low - ss_low, FAIL); } /* end if */ else low = ss_low; /* Add overlapping elements */ udata->nelem += high - low + 1; } /* end else */ /* Advance spans */ if (ss_span->high == sis_span->high) { /* Advance both spans */ ss_span = ss_span->next; if (ss_span) ss_low = ss_span->low; sis_span = sis_span->next; if (sis_span) sis_low = sis_span->low; } /* end if */ else if (ss_span->high == high) { /* Advance source span */ HDassert(ss_span->high < sis_span->high); sis_low = high + 1; ss_span = ss_span->next; if (ss_span) ss_low = ss_span->low; } /* end if */ else { /* Advance source intersect span */ HDassert(ss_span->high > sis_span->high); ss_low = high + 1; sis_span = sis_span->next; if (sis_span) sis_low = sis_span->low; } /* end else */ } /* end if */ else { /* Advance spans */ if (ss_span->high < sis_low) { /* Add skipped elements */ if (ss_span->down) H5S_HYPER_PROJ_INT_ADD_SKIP( udata, H5S__hyper_spans_nelem_helper(ss_span->down, 0, udata->op_gen) * (ss_span->high - ss_low + 1), FAIL); else H5S_HYPER_PROJ_INT_ADD_SKIP(udata, ss_span->high - ss_low + 1, FAIL); /* Advance source span */ ss_span = ss_span->next; if (ss_span) ss_low = ss_span->low; } /* end if */ else { /* Advance source intersect span */ HDassert(ss_low > sis_span->high); sis_span = sis_span->next; if (sis_span) sis_low = sis_span->low; } /* end else */ } /* end else */ } while (ss_span && sis_span); if (ss_span && !((depth == 0) && (u == count - 1))) { /* Count remaining elements in ss_span_info */ if (ss_span->down) { H5S_HYPER_PROJ_INT_ADD_SKIP( udata, H5S__hyper_spans_nelem_helper(ss_span->down, 0, udata->op_gen) * (ss_span->high - ss_low + 1), FAIL); ss_span = ss_span->next; while (ss_span) { H5S_HYPER_PROJ_INT_ADD_SKIP( udata, H5S__hyper_spans_nelem_helper(ss_span->down, 0, udata->op_gen) * (ss_span->high - ss_span->low + 1), FAIL); ss_span = ss_span->next; } /* end while */ } /* end if */ else { H5S_HYPER_PROJ_INT_ADD_SKIP(udata, ss_span->high - ss_low + 1, FAIL); ss_span = ss_span->next; while (ss_span) { H5S_HYPER_PROJ_INT_ADD_SKIP(udata, ss_span->high - ss_span->low + 1, FAIL); ss_span = ss_span->next; } /* end while */ } /* end else */ } /* end if */ /* Check if the projected space was not changed since we started the * first iteration of the loop, if so we do not need to continue * looping and can just copy the result */ if (udata->ps_clean_bitmap & (((uint32_t)1) << depth)) { HDassert(u == 0); if (udata->skip == old_skip) { /* First case: algorithm added only elements */ HDassert(udata->nelem >= old_nelem); udata->nelem += (count - 1) * (udata->nelem - old_nelem); } /* end if */ else if (udata->nelem == 0) { /* Second case: algorithm added only skip. In this case, * nelem must be 0 since otherwise adding skip would have * triggered a change in the projected space */ HDassert(old_nelem == 0); HDassert(udata->skip > old_skip); udata->skip += (count - 1) * (udata->skip - old_skip); } /* end if */ else { /* Third case: agorithm added skip and nelem (in that * order). Add the same skip and nelem once for each item * remaining in count. */ hsize_t skip_add; hsize_t nelem_add; HDassert(udata->nelem > 0); HDassert(udata->skip > old_skip); HDassert(old_nelem == 0); skip_add = udata->skip - old_skip; nelem_add = udata->nelem - old_nelem; for (u = 1; u < count; u++) { H5S_HYPER_PROJ_INT_ADD_SKIP(udata, skip_add, FAIL); udata->nelem += nelem_add; } /* end for */ } /* end else */ /* End loop since we already took care of it */ break; } /* end if */ } /* end for */ } /* end if */ else if (depth > 0) /* Just count skipped elements */ H5S_HYPER_PROJ_INT_ADD_SKIP( udata, H5S__hyper_spans_nelem_helper((H5S_hyper_span_info_t *)ss_span_info, 0, udata->op_gen) * count, FAIL); /* Casting away const OK -NAF */ /* Clean up if we are done */ if (depth == 0) { /* Add remaining elements */ if (udata->nelem > 0) if (H5S__hyper_proj_int_build_proj(udata) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't add elements to projected selection") /* Append remaining span trees */ for (u = udata->ds_rank - 1; u > 0; u--) if (udata->ps_span_info[u]) { if (H5S__hyper_append_span(&udata->ps_span_info[u - 1], udata->ds_rank - u + 1, udata->ds_low[u - 1], udata->ds_low[u - 1], udata->ps_span_info[u]) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTAPPEND, FAIL, "can't allocate hyperslab span") H5S__hyper_free_span_info(udata->ps_span_info[u]); udata->ps_span_info[u] = NULL; } /* end if */ } /* end if */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_proj_int_iterate() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_project_intersection PURPOSE Projects the intersection of of the selections of src_space and src_intersect_space within the selection of src_space as a selection within the selection of dst_space USAGE herr_t H5S__hyper_project_intersection(src_space,dst_space,src_intersect_space,proj_space,share_selection) H5S_t *src_space; IN: Selection that is mapped to dst_space, and intersected with src_intersect_space H5S_t *dst_space; IN: Selection that is mapped to src_space, and which contains the result H5S_t *src_intersect_space; IN: Selection whose intersection with src_space is projected to dst_space to obtain the result H5S_t *proj_space; OUT: Will contain the result (intersection of src_intersect_space and src_space projected from src_space to dst_space) after the operation hbool_t share_selection; IN: Whether we are allowed to share structures inside dst_space with proj_space RETURNS Non-negative on success/Negative on failure. DESCRIPTION Projects the intersection of of the selections of src_space and src_intersect_space within the selection of src_space as a selection within the selection of dst_space. The result is placed in the selection of proj_space. Note src_space, dst_space, and src_intersect_space do not need to use hyperslab selections, but they cannot use point selections. The result is always a hyperslab or none selection. Note also that proj_space can share some span trees with dst_space, so proj_space must not be subsequently modified if dst_space must be preserved. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5S__hyper_project_intersection(const H5S_t *src_space, const H5S_t *dst_space, const H5S_t *src_intersect_space, H5S_t *proj_space, hbool_t share_selection) { H5S_hyper_project_intersect_ud_t udata; /* User data for subroutines */ const H5S_hyper_span_info_t * ss_span_info; const H5S_hyper_span_info_t * ds_span_info; H5S_hyper_span_info_t * ss_span_info_buf = NULL; H5S_hyper_span_info_t * ds_span_info_buf = NULL; herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_PACKAGE /* Check parameters */ HDassert(src_space); HDassert(dst_space); HDassert(src_intersect_space); HDassert(proj_space); /* Assert that src_space and src_intersect_space have same rank and there * are no point selections */ HDassert(H5S_GET_EXTENT_NDIMS(src_space) == H5S_GET_EXTENT_NDIMS(src_intersect_space)); HDassert(H5S_GET_SELECT_NPOINTS(src_space) == H5S_GET_SELECT_NPOINTS(dst_space)); HDassert(H5S_GET_SELECT_TYPE(src_space) != H5S_SEL_POINTS); HDassert(H5S_GET_SELECT_TYPE(dst_space) != H5S_SEL_POINTS); HDassert(H5S_GET_SELECT_TYPE(src_intersect_space) == H5S_SEL_HYPERSLABS); /* Set up ss_span_info */ if (H5S_GET_SELECT_TYPE(src_space) == H5S_SEL_HYPERSLABS) { /* Make certain the selection has a span tree */ if (NULL == src_space->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans((H5S_t *)src_space) < 0) /* Casting away const OK -NAF */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "can't construct span tree for source hyperslab selection") /* Simply point to existing span tree */ ss_span_info = src_space->select.sel_info.hslab->span_lst; } /* end if */ else { /* Create temporary span tree from all selection */ HDassert(H5S_GET_SELECT_TYPE(src_space) == H5S_SEL_ALL); if (NULL == (ss_span_info_buf = H5S__hyper_make_spans(H5S_GET_EXTENT_NDIMS(src_space), H5S_hyper_zeros_g, H5S_hyper_zeros_g, H5S_hyper_ones_g, src_space->extent.size))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "can't create span tree for ALL source space") ss_span_info = ss_span_info_buf; } /* end else */ /* Set up ds_span_info */ if (H5S_GET_SELECT_TYPE(dst_space) == H5S_SEL_HYPERSLABS) { /* Make certain the selection has a span tree */ if (NULL == dst_space->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans((H5S_t *)dst_space) < 0) /* Casting away const OK -NAF */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "can't construct span tree for dsetination hyperslab selection") /* Simply point to existing span tree */ ds_span_info = dst_space->select.sel_info.hslab->span_lst; } /* end if */ else { /* Create temporary span tree from all selection */ HDassert(H5S_GET_SELECT_TYPE(dst_space) == H5S_SEL_ALL); if (NULL == (ds_span_info_buf = H5S__hyper_make_spans(H5S_GET_EXTENT_NDIMS(dst_space), H5S_hyper_zeros_g, H5S_hyper_zeros_g, H5S_hyper_ones_g, dst_space->extent.size))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "can't create span tree for ALL destination space") ds_span_info = ds_span_info_buf; } /* end else */ /* Make certain the source intersect selection has a span tree */ if (NULL == src_intersect_space->select.sel_info.hslab->span_lst) if (H5S__hyper_generate_spans((H5S_t *)src_intersect_space) < 0) /* Casting away const OK -NAF */ HGOTO_ERROR(H5E_DATASPACE, H5E_UNINITIALIZED, FAIL, "can't construct span tree for source intersect hyperslab selection") /* Initialize udata */ /* We will use op_info[0] for nelem and op_info[1] for copied spans */ HDmemset(&udata, 0, sizeof(udata)); udata.ds_span[0] = ds_span_info->head; udata.ds_low[0] = udata.ds_span[0]->low; udata.ss_rank = H5S_GET_EXTENT_NDIMS(src_space); udata.ds_rank = H5S_GET_EXTENT_NDIMS(dst_space); udata.op_gen = H5S__hyper_get_op_gen(); udata.share_selection = share_selection; /* Iterate over selections and build projected span tree */ if (H5S__hyper_proj_int_iterate(ss_span_info, src_intersect_space->select.sel_info.hslab->span_lst, 1, 0, &udata) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOMPARE, FAIL, "selection iteration failed") /* Remove current selection from proj_space */ if (H5S_SELECT_RELEASE(proj_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't release selection") /* Check for elements in projected space */ if (udata.ps_span_info[0]) { /* Allocate space for the hyperslab selection information (note this sets * diminfo_valid to FALSE, diminfo arrays to 0, and span list to NULL) */ if (NULL == (proj_space->select.sel_info.hslab = H5FL_CALLOC(H5S_hyper_sel_t))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTALLOC, FAIL, "can't allocate hyperslab info") /* Set selection type */ proj_space->select.type = H5S_sel_hyper; /* Set unlim_dim */ proj_space->select.sel_info.hslab->unlim_dim = -1; /* Set span tree */ proj_space->select.sel_info.hslab->span_lst = udata.ps_span_info[0]; udata.ps_span_info[0] = NULL; /* Set the number of elements in current selection */ proj_space->select.num_elem = H5S__hyper_spans_nelem(proj_space->select.sel_info.hslab->span_lst); /* Attempt to build "optimized" start/stride/count/block information * from resulting hyperslab span tree. */ H5S__hyper_rebuild(proj_space); } /* end if */ else /* If we did not add anything to proj_space, select none instead */ if (H5S_select_none(proj_space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't convert selection") done: /* Free ss_span_info_buf */ if (ss_span_info_buf) { H5S__hyper_free_span_info(ss_span_info_buf); ss_span_info_buf = NULL; } /* end if */ /* Free ds_span_info_buf */ if (ds_span_info_buf) { H5S__hyper_free_span_info(ds_span_info_buf); ds_span_info_buf = NULL; } /* end if */ /* Cleanup on error */ if (ret_value < 0) { unsigned u; /* Free span trees */ for (u = 0; u < udata.ds_rank; u++) if (udata.ps_span_info[u]) { H5S__hyper_free_span_info(udata.ps_span_info[u]); udata.ps_span_info[u] = NULL; } /* end if */ } /* end if */ #ifndef NDEBUG /* Verify there are no more span trees */ { unsigned u; for (u = 0; u < H5S_MAX_RANK; u++) HDassert(!udata.ps_span_info[u]); } /* end block */ #endif /* NDEBUG */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_project_intersection() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_get_clip_diminfo PURPOSE Calculates the count and block required to clip the specified unlimited dimension to include clip_size. The returned selection may extent beyond clip_size. USAGE void H5S__hyper_get_clip_diminfo(start,stride,count,block,clip_size) hsize_t start; IN: Start of hyperslab in unlimited dimension hsize_t stride; IN: Stride of hyperslab in unlimited dimension hsize_t *count; IN/OUT: Count of hyperslab in unlimited dimension hsize_t *block; IN/OUT: Block of hyperslab in unlimited dimension hsize_t clip_size; IN: Extent that hyperslab will be clipped to RETURNS Non-negative on success/Negative on failure. DESCRIPTION This function recalculates the internal description of the hyperslab to make the unlimited dimension extend to the specified extent. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static void H5S__hyper_get_clip_diminfo(hsize_t start, hsize_t stride, hsize_t *count, hsize_t *block, hsize_t clip_size) { FUNC_ENTER_STATIC_NOERR /* Check for selection outside clip size */ if (start >= clip_size) { if (*block == H5S_UNLIMITED) *block = 0; else *count = 0; } /* end if */ /* Check for single block in unlimited dimension */ else if ((*block == H5S_UNLIMITED) || (*block == stride)) { /* Calculate actual block size for this clip size */ *block = clip_size - start; *count = (hsize_t)1; } /* end if */ else { HDassert(*count == H5S_UNLIMITED); /* Calculate initial count (last block may be partial) */ *count = (clip_size - start + stride - (hsize_t)1) / stride; HDassert(*count > (hsize_t)0); } /* end else */ FUNC_LEAVE_NOAPI_VOID } /* end H5S__hyper_get_clip_diminfo() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_clip_unlim PURPOSE Clips the unlimited dimension of the hyperslab selection to the specified size USAGE void H5S_hyper_clip_unlim(space,clip_size) H5S_t *space, IN/OUT: Unlimited space to clip hsize_t clip_size; IN: Extent that hyperslab will be clipped to RETURNS Non-negative on success/Negative on failure. DESCRIPTION This function changes the unlimited selection into a fixed-dimension selection with the extent of the formerly unlimited dimension specified by clip_size. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this function does not take the offset into account. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5S_hyper_clip_unlim(H5S_t *space, hsize_t clip_size) { H5S_hyper_sel_t *hslab = NULL; /* Convenience pointer to hyperslab info */ hsize_t orig_count; /* Original count in unlimited dimension */ int orig_unlim_dim; /* Original unliminted dimension */ H5S_hyper_dim_t *diminfo = NULL; /* Convenience pointer to diminfo.opt in unlimited dimension */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI(FAIL) /* Check parameters */ HDassert(space); hslab = space->select.sel_info.hslab; HDassert(hslab); HDassert(hslab->unlim_dim >= 0); HDassert(!hslab->span_lst); /* Save original unlimited dimension */ orig_unlim_dim = hslab->unlim_dim; /* Set up convenience pointer */ diminfo = &hslab->diminfo.opt[orig_unlim_dim]; /* Save original count in unlimited dimension */ orig_count = diminfo->count; /* Get initial diminfo */ H5S__hyper_get_clip_diminfo(diminfo->start, diminfo->stride, &diminfo->count, &diminfo->block, clip_size); /* Selection is no longer unlimited */ space->select.sel_info.hslab->unlim_dim = -1; /* Check for nothing returned */ if ((diminfo->block == 0) || (diminfo->count == 0)) { /* Convert to "none" selection */ if (H5S_select_none(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTDELETE, FAIL, "can't convert selection") /* Reset the convenience pointers */ hslab = NULL; diminfo = NULL; } /* end if */ /* Check for single block in unlimited dimension */ else if (orig_count == (hsize_t)1) { /* Calculate number of elements */ space->select.num_elem = diminfo->block * hslab->num_elem_non_unlim; /* Mark that diminfo.opt is valid */ hslab->diminfo_valid = H5S_DIMINFO_VALID_YES; } /* end if */ else { /* Calculate number of elements */ space->select.num_elem = diminfo->count * diminfo->block * hslab->num_elem_non_unlim; /* Check if last block is partial. If superset is set, just keep the * last block complete to speed computation. */ HDassert(clip_size > diminfo->start); if (((diminfo->stride * (diminfo->count - (hsize_t)1)) + diminfo->block) > (clip_size - diminfo->start)) { hsize_t start[H5S_MAX_RANK]; hsize_t block[H5S_MAX_RANK]; unsigned u; /* Last block is partial, need to construct compound selection */ /* Fill start with zeros */ HDmemset(start, 0, sizeof(start)); /* Set block to clip_size in unlimited dimension, H5S_MAX_SIZE in * others so only unlimited dimension is clipped */ for (u = 0; u < space->extent.rank; u++) if ((int)u == orig_unlim_dim) block[u] = clip_size; else block[u] = H5S_MAX_SIZE; /* Generate span tree in selection */ if (!hslab->span_lst) if (H5S__hyper_generate_spans(space) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, FAIL, "unable to generate span tree") /* Indicate that the regular dimensions are no longer valid */ hslab->diminfo_valid = H5S_DIMINFO_VALID_NO; /* "And" selection with calculated block to perform clip operation */ if (H5S__generate_hyperslab(space, H5S_SELECT_AND, start, H5S_hyper_ones_g, H5S_hyper_ones_g, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINSERT, FAIL, "can't generate hyperslabs") } /* end if */ else /* Last block is complete, simply mark that diminfo.opt is valid */ hslab->diminfo_valid = H5S_DIMINFO_VALID_YES; } /* end else */ /* Update the upper bound, if the diminfo is valid */ if (hslab && (H5S_DIMINFO_VALID_YES == hslab->diminfo_valid)) hslab->diminfo.high_bounds[orig_unlim_dim] = hslab->diminfo.opt[orig_unlim_dim].start + hslab->diminfo.opt[orig_unlim_dim].stride * (hslab->diminfo.opt[orig_unlim_dim].count - 1) + (hslab->diminfo.opt[orig_unlim_dim].block - 1); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_clip_unlim() */ /*-------------------------------------------------------------------------- NAME H5S__hyper_get_clip_extent_real PURPOSE Gets the extent a space should be clipped to in order to contain the specified number of slices in the unlimited dimension USAGE hsize_t H5S__hyper_get_clip_extent_real(clip_space,num_slices,incl_trail) const H5S_t *clip_space, IN: Space that clip size will be calculated based on hsize_t num_slizes, IN: Number of slices clip_space should contain when clipped hbool_t incl_trail; IN: Whether to include trailing unselected space RETURNS Clip extent to match num_slices (never fails) DESCRIPTION Calculates and returns the extent that clip_space should be clipped to (via H5S_hyper_clip_unlim) in order for it to contain num_slices slices in the unlimited dimension. If the clipped selection would end immediately before a section of unselected space (i.e. at the end of a block), then if incl_trail is TRUE, the returned clip extent is selected to include that trailing "blank" space, otherwise it is selected to end at the end before the blank space. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this assumes the offset has been normalized. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ static hsize_t H5S__hyper_get_clip_extent_real(const H5S_t *clip_space, hsize_t num_slices, hbool_t incl_trail) { const H5S_hyper_dim_t *diminfo; /* Convenience pointer to opt_unlim_diminfo in unlimited dimension */ hsize_t count; hsize_t rem_slices; hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_STATIC_NOERR /* Check parameters */ HDassert(clip_space); HDassert(clip_space->select.sel_info.hslab); HDassert(clip_space->select.sel_info.hslab->unlim_dim >= 0); diminfo = &clip_space->select.sel_info.hslab->diminfo.opt[clip_space->select.sel_info.hslab->unlim_dim]; if (num_slices == 0) ret_value = incl_trail ? diminfo->start : 0; else if ((diminfo->block == H5S_UNLIMITED) || (diminfo->block == diminfo->stride)) /* Unlimited block, just set the extent large enough for the block size * to match num_slices */ ret_value = diminfo->start + num_slices; else { /* Unlimited count, need to match extent so a block (possibly) gets cut * off so the number of slices matches num_slices */ HDassert(diminfo->count == H5S_UNLIMITED); /* Calculate number of complete blocks in clip_space */ count = num_slices / diminfo->block; /* Calculate slices remaining */ rem_slices = num_slices - (count * diminfo->block); if (rem_slices > 0) /* Must end extent in middle of partial block (or beginning of empty * block if include_trailing_space and rem_slices == 0) */ ret_value = diminfo->start + (count * diminfo->stride) + rem_slices; else { if (incl_trail) /* End extent just before first missing block */ ret_value = diminfo->start + (count * diminfo->stride); else /* End extent at end of last block */ ret_value = diminfo->start + ((count - (hsize_t)1) * diminfo->stride) + diminfo->block; } /* end else */ } /* end else */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5S__hyper_get_clip_extent_real() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_get_clip_extent PURPOSE Gets the extent a space should be clipped to in order to contain the same number of elements as another space USAGE hsize_t H5S__hyper_get_clip_extent(clip_space,match_space,incl_trail) const H5S_t *clip_space, IN: Space that clip size will be calculated based on const H5S_t *match_space, IN: Space containing the same number of elements as clip_space should after clipping hbool_t incl_trail; IN: Whether to include trailing unselected space RETURNS Calculated clip extent (never fails) DESCRIPTION Calculates and returns the extent that clip_space should be clipped to (via H5S_hyper_clip_unlim) in order for it to contain the same number of elements as match_space. If the clipped selection would end immediately before a section of unselected space (i.e. at the end of a block), then if incl_trail is TRUE, the returned clip extent is selected to include that trailing "blank" space, otherwise it is selected to end at the end before the blank space. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this assumes the offset has been normalized. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hsize_t H5S_hyper_get_clip_extent(const H5S_t *clip_space, const H5S_t *match_space, hbool_t incl_trail) { hsize_t num_slices; /* Number of slices in unlimited dimension */ hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_NOAPI(0) /* Check parameters */ HDassert(clip_space); HDassert(match_space); HDassert(clip_space->select.sel_info.hslab->unlim_dim >= 0); /* Check for "none" match space */ if (match_space->select.type->type == H5S_SEL_NONE) num_slices = (hsize_t)0; else { HDassert(match_space->select.type->type == H5S_SEL_HYPERSLABS); HDassert(match_space->select.sel_info.hslab); /* Calculate number of slices */ num_slices = match_space->select.num_elem / clip_space->select.sel_info.hslab->num_elem_non_unlim; HDassert((match_space->select.num_elem % clip_space->select.sel_info.hslab->num_elem_non_unlim) == 0); } /* end else */ /* Call "real" get_clip_extent function */ ret_value = H5S__hyper_get_clip_extent_real(clip_space, num_slices, incl_trail); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_get_clip_extent() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_get_clip_extent_match PURPOSE Gets the extent a space should be clipped to in order to contain the same number of elements as another unlimited space that has been clipped to a different extent USAGE hsize_t H5S__hyper_get_clip_extent_match(clip_space,match_space,match_clip_size,incl_trail) const H5S_t *clip_space, IN: Space that clip size will be calculated based on const H5S_t *match_space, IN: Space that, after being clipped to match_clip_size, contains the same number of elements as clip_space should after clipping hsize_t match_clip_size, IN: Extent match_space would be clipped to to match the number of elements in clip_space hbool_t incl_trail; IN: Whether to include trailing unselected space RETURNS Calculated clip extent (never fails) DESCRIPTION Calculates and returns the extent that clip_space should be clipped to (via H5S_hyper_clip_unlim) in order for it to contain the same number of elements as match_space would have after being clipped to match_clip_size. If the clipped selection would end immediately before a section of unselected space (i.e. at the end of a block), then if incl_trail is TRUE, the returned clip extent is selected to include that trailing "blank" space, otherwise it is selected to end at the end before the blank space. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this assumes the offset has been normalized. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hsize_t H5S_hyper_get_clip_extent_match(const H5S_t *clip_space, const H5S_t *match_space, hsize_t match_clip_size, hbool_t incl_trail) { const H5S_hyper_dim_t *match_diminfo; /* Convenience pointer to opt_unlim_diminfo in unlimited dimension in match_space */ hsize_t count; /* Temporary count */ hsize_t block; /* Temporary block */ hsize_t num_slices; /* Number of slices in unlimited dimension */ hsize_t ret_value = 0; /* Return value */ FUNC_ENTER_NOAPI(0) /* Check parameters */ HDassert(clip_space); HDassert(match_space); HDassert(clip_space->select.sel_info.hslab); HDassert(match_space->select.sel_info.hslab); HDassert(clip_space->select.sel_info.hslab->unlim_dim >= 0); HDassert(match_space->select.sel_info.hslab->unlim_dim >= 0); HDassert(clip_space->select.sel_info.hslab->num_elem_non_unlim == match_space->select.sel_info.hslab->num_elem_non_unlim); match_diminfo = &match_space->select.sel_info.hslab->diminfo.opt[match_space->select.sel_info.hslab->unlim_dim]; /* Get initial count and block */ count = match_diminfo->count; block = match_diminfo->block; H5S__hyper_get_clip_diminfo(match_diminfo->start, match_diminfo->stride, &count, &block, match_clip_size); /* Calculate number of slices */ /* Check for nothing returned */ if ((block == 0) || (count == 0)) num_slices = (hsize_t)0; /* Check for single block in unlimited dimension */ else if (count == (hsize_t)1) num_slices = block; else { /* Calculate initial num_slices */ num_slices = block * count; /* Check for partial last block */ HDassert(match_clip_size >= match_diminfo->start); if (((match_diminfo->stride * (count - (hsize_t)1)) + block) > (match_clip_size - match_diminfo->start)) { /* Subtract slices missing from last block */ HDassert((((match_diminfo->stride * (count - (hsize_t)1)) + block) - (match_clip_size - match_diminfo->start)) < num_slices); num_slices -= ((match_diminfo->stride * (count - (hsize_t)1)) + block) - (match_clip_size - match_diminfo->start); } /* end if */ } /* end else */ /* Call "real" get_clip_extent function */ ret_value = H5S__hyper_get_clip_extent_real(clip_space, num_slices, incl_trail); done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_get_clip_extent_match() */ /*-------------------------------------------------------------------------- NAME H5S_hyper_get_unlim_block PURPOSE Get the nth block in the unlimited dimension USAGE H5S_t *H5S_hyper_get_unlim_block(space,block_index) const H5S_t *space, IN: Space with unlimited selection hsize_t block_index, IN: Index of block to return in unlimited dimension hbool_t incl_trail; IN: Whether to include trailing unselected space RETURNS New space on success/NULL on failure. DESCRIPTION Returns a space containing only the block_indexth block in the unlimited dimension on space. All blocks in all other dimensions are preserved. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this assumes the offset has been normalized. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ H5S_t * H5S_hyper_get_unlim_block(const H5S_t *space, hsize_t block_index) { H5S_hyper_sel_t *hslab; /* Convenience pointer to hyperslab info */ H5S_t * space_out = NULL; /* Dataspace to return */ hsize_t start[H5S_MAX_RANK]; /* Hyperslab selection info for unlim. selection */ hsize_t stride[H5S_MAX_RANK]; hsize_t count[H5S_MAX_RANK]; hsize_t block[H5S_MAX_RANK]; unsigned u; /* Local index variable */ H5S_t * ret_value = NULL; /* Return value */ FUNC_ENTER_NOAPI(NULL) /* Check parameters */ HDassert(space); hslab = space->select.sel_info.hslab; HDassert(hslab); HDassert(hslab->unlim_dim >= 0); HDassert(hslab->diminfo.opt[hslab->unlim_dim].count == H5S_UNLIMITED); /* Set start to select block_indexth block in unlimited dimension and set * count to 1 in that dimension to only select that block. Copy all other * diminfo parameters. */ for (u = 0; u < space->extent.rank; u++) { if ((int)u == hslab->unlim_dim) { start[u] = hslab->diminfo.opt[u].start + (block_index * hslab->diminfo.opt[u].stride); count[u] = (hsize_t)1; } /* end if */ else { start[u] = hslab->diminfo.opt[u].start; count[u] = hslab->diminfo.opt[u].count; } /* end else */ stride[u] = hslab->diminfo.opt[u].stride; block[u] = hslab->diminfo.opt[u].block; } /* end for */ /* Create output space, copy extent */ if (NULL == (space_out = H5S_create(H5S_SIMPLE))) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCREATE, NULL, "unable to create output dataspace") if (H5S__extent_copy_real(&space_out->extent, &space->extent, TRUE) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTCOPY, NULL, "unable to copy destination space extent") /* Select block as defined by start/stride/count/block computed above */ if (H5S_select_hyperslab(space_out, H5S_SELECT_SET, start, stride, count, block) < 0) HGOTO_ERROR(H5E_DATASPACE, H5E_CANTINIT, NULL, "can't select hyperslab") /* Set return value */ ret_value = space_out; done: /* Free space on error */ if (!ret_value) if (space_out && H5S_close(space_out) < 0) HDONE_ERROR(H5E_DATASPACE, H5E_CANTRELEASE, NULL, "unable to release dataspace") FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_get_unlim_block */ /*-------------------------------------------------------------------------- NAME H5S_hyper_get_first_inc_block PURPOSE Get the index of the first incomplete block in the specified extent USAGE hsize_t H5S_hyper_get_first_inc_block(space,clip_size,partial) const H5S_t *space, IN: Space with unlimited selection hsize_t clip_size, IN: Extent space would be clipped to hbool_t *partial; OUT: Whether the ret_valueth block (first incomplete block) is partial RETURNS Index of first incomplete block in clip_size (never fails). DESCRIPTION Calculates and returns the index (as would be passed to H5S_hyper_get_unlim_block()) of the first block in the unlimited dimension of space which would be incomplete or missing when space is clipped to clip_size. partial is set to TRUE if the first incomplete block is partial, and FALSE if the first incomplete block is missing. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note this assumes the offset has been normalized. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ hsize_t H5S_hyper_get_first_inc_block(const H5S_t *space, hsize_t clip_size, hbool_t *partial) { H5S_hyper_sel_t *hslab; /* Convenience pointer to hyperslab info */ H5S_hyper_dim_t *diminfo; /* Convenience pointer to diminfo in unlimited dimension */ hsize_t ret_value = 0; FUNC_ENTER_NOAPI(0) /* Check parameters */ HDassert(space); hslab = space->select.sel_info.hslab; HDassert(hslab); HDassert(hslab->unlim_dim >= 0); HDassert(hslab->diminfo.opt[hslab->unlim_dim].count == H5S_UNLIMITED); diminfo = &hslab->diminfo.opt[hslab->unlim_dim]; /* Check for selection outside of clip_size */ if (diminfo->start >= clip_size) { ret_value = 0; if (partial) partial = FALSE; } /* end if */ else { /* Calculate index of first incomplete block */ ret_value = (clip_size - diminfo->start + diminfo->stride - diminfo->block) / diminfo->stride; if (partial) { /* Check for partial block */ if ((diminfo->stride * ret_value) < (clip_size - diminfo->start)) *partial = TRUE; else *partial = FALSE; } /* end if */ } /* end else */ done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5S_hyper_get_first_inc_block */ /*-------------------------------------------------------------------------- NAME H5Sis_regular_hyperslab PURPOSE Determine if a hyperslab selection is regular USAGE htri_t H5Sis_regular_hyperslab(dsid) hid_t dsid; IN: Dataspace ID of hyperslab selection to query RETURNS TRUE/FALSE for hyperslab selection, FAIL on error or when querying other selection types. DESCRIPTION If a hyperslab can be represented as a single call to H5Sselect_hyperslab, with the H5S_SELECT_SET option, it is regular. If the hyperslab selection would require multiple calls to H5Sselect_hyperslab, it is irregular. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ htri_t H5Sis_regular_hyperslab(hid_t spaceid) { H5S_t *space; /* Dataspace to query */ htri_t ret_value; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE1("t", "i", spaceid); /* Check args */ if (NULL == (space = (H5S_t *)H5I_object_verify(spaceid, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (H5S_GET_SELECT_TYPE(space) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a hyperslab selection") ret_value = H5S__hyper_is_regular(space); done: FUNC_LEAVE_API(ret_value) } /* end H5Sis_regular_hyperslab() */ /*-------------------------------------------------------------------------- NAME H5Sget_regular_hyperslab PURPOSE Retrieve a regular hyperslab selection USAGE herr_t H5Sget_regular_hyperslab(dsid, start, stride, block, count) hid_t dsid; IN: Dataspace ID of hyperslab selection to query hsize_t start[]; OUT: Offset of start of hyperslab hsize_t stride[]; OUT: Hyperslab stride hsize_t count[]; OUT: Number of blocks included in hyperslab hsize_t block[]; OUT: Size of block in hyperslab RETURNS Non-negative on success/Negative on failure. (It is an error to query the regular hyperslab selections for non-regular hyperslab selections) DESCRIPTION Retrieve the start/stride/count/block for a regular hyperslab selection. GLOBAL VARIABLES COMMENTS, BUGS, ASSUMPTIONS Note that if a hyperslab is originally regular, then becomes irregular through selection operations, and then becomes regular again, the new final regular selection may be equivalent but not identical to the original regular selection. EXAMPLES REVISION LOG --------------------------------------------------------------------------*/ herr_t H5Sget_regular_hyperslab(hid_t spaceid, hsize_t start[] /*out*/, hsize_t stride[] /*out*/, hsize_t count[] /*out*/, hsize_t block[] /*out*/) { H5S_t * space; /* Dataspace to query */ unsigned u; /* Local index variable */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_API(FAIL) H5TRACE5("e", "ixxxx", spaceid, start, stride, count, block); /* Check args */ if (NULL == (space = (H5S_t *)H5I_object_verify(spaceid, H5I_DATASPACE))) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a dataspace") if (H5S_GET_SELECT_TYPE(space) != H5S_SEL_HYPERSLABS) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a hyperslab selection") if (TRUE != H5S__hyper_is_regular(space)) HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "not a regular hyperslab selection") /* Retrieve hyperslab parameters */ if (start) for (u = 0; u < space->extent.rank; u++) start[u] = space->select.sel_info.hslab->diminfo.app[u].start; if (stride) for (u = 0; u < space->extent.rank; u++) stride[u] = space->select.sel_info.hslab->diminfo.app[u].stride; if (count) for (u = 0; u < space->extent.rank; u++) count[u] = space->select.sel_info.hslab->diminfo.app[u].count; if (block) for (u = 0; u < space->extent.rank; u++) block[u] = space->select.sel_info.hslab->diminfo.app[u].block; done: FUNC_LEAVE_API(ret_value) } /* end H5Sget_regular_hyperslab() */
43.842207
110
0.550332
[ "shape", "vector" ]
a5c23771b6d34ae2ada291d7f540f7db8264102f
2,873
h
C
include/mesh.h
cb-cities/pipe-network
e0d4f7dab1e82e0706b33918a815d8633202c479
[ "MIT" ]
2
2019-04-08T20:47:50.000Z
2019-05-03T18:58:04.000Z
include/mesh.h
cb-cities/pipe-network
e0d4f7dab1e82e0706b33918a815d8633202c479
[ "MIT" ]
25
2018-05-22T12:47:19.000Z
2020-06-19T21:34:04.000Z
include/mesh.h
cb-cities/pipe-network
e0d4f7dab1e82e0706b33918a815d8633202c479
[ "MIT" ]
4
2018-07-16T17:20:19.000Z
2019-01-17T22:08:33.000Z
#ifndef PIPE_NETWORK_MESH_H_ #define PIPE_NETWORK_MESH_H_ #include <cmath> #include <array> #include <exception> #include <iostream> #include <map> #include <memory> #include <vector> #include "node.h" #include "pipe.h" #include "settings.h" namespace pipenetwork { //! Mesh class //! \brief Class for mesh that contains node and pipe pointers class Mesh { public: // Constructor with id //! \param[in] id mesh id explicit Mesh(unsigned id) : id_{id} {}; //! Destructor ~Mesh() = default; //! Return id //! \retval id_ id of the mesh unsigned id() const { return id_; } //! Create nodal pointers and assign indices based on coordinates //! \param[in] coords vector of the coordinates of the nodes void create_nodes(const std::vector<Eigen::Vector3d>& coords); //! Create a pipe pointers and assign indices based on the nodes at its ends //! \param[in] nodeid1 and nodeid2 indices of the nodes at pipe ends //! \retval status to check whether all input pipe created successfully bool create_pipes(const std::vector<std::pair<Index, Index>>& nodeids, const std::vector<double>& diameter, const std::vector<double>& roughness, const std::vector<bool>& pipe_status); //! Return the number of nodes in the mesh //! \retval nodes_.size() number of nodes unsigned nnodes() const { return nodes_.size(); } //! Return the number of pipes in the mesh //! \retval pipes_.size() number of pipes unsigned npipes() const { return pipes_.size(); } //! Remove unconnected nodes from the mesh void remove_unconnected_nodes(); //! Initialize discharges in pipes void initialize_pipe_discharge( const std::vector<std::pair<Index, double>>& init_discharge = std::vector<std::pair<Index, double>>()); void initialize_pipe_discharge(double init_discharge); //! Assign initial heads/elevation for nodes //! \param[in] node_head vector of pair of nodal index and initial nodal head void assign_node_head(const std::vector<std::pair<Index, double>>& node_head); void assign_node_elevation( const std::vector<std::pair<Index, double>>& node_head); //! Assign initial demand for nodes that have known discharge //! \param[in] node_discharge vector of pair of nodal index and initial //! discharge void assign_node_demand( const std::vector<std::pair<Index, double>>& node_discharge); //! Make MatrixAssembler a friend class of mesh friend class MatrixAssembler; private: //! mesh id unsigned id_{std::numeric_limits<unsigned>::max()}; //! nodal id and corresponding nodal pointer std::map<Index, std::shared_ptr<pipenetwork::Node>> nodes_; //! pipe id and corresponding pipe pointer std::map<Index, std::shared_ptr<pipenetwork::Pipe>> pipes_; }; } // namespace pipenetwork #endif // PIPE_NETWORK_MESH_H_
31.571429
80
0.699617
[ "mesh", "vector" ]
a5c97f6f4af88c9a52ac34a6cf6987f52ddc6ba1
1,722
h
C
PacketParser.h
msimms/LibPacketParser
6aa3ca87a5b4dc3b37499f01e242f78f4367ff26
[ "MIT" ]
null
null
null
PacketParser.h
msimms/LibPacketParser
6aa3ca87a5b4dc3b37499f01e242f78f4367ff26
[ "MIT" ]
null
null
null
PacketParser.h
msimms/LibPacketParser
6aa3ca87a5b4dc3b37499f01e242f78f4367ff26
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2018 Michael J Simms. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <vector> #include "NetworkDefinitions.h" namespace PacketParser { typedef enum HeaderType { HEADER_ETHER = 0, HEADER_IPV4, HEADER_IPV6, HEADER_TCP, HEADER_UDP, HEADER_ARP, HEADER_ICMPV4, HEADER_ICMPV6, HEADER_DNS, HEADER_MDNS, HEADER_HTTP, HEADER_HTTPS } HeaderType; typedef std::pair<HeaderType, const uint8_t*> HeaderRef; // The second item in the pair is a pointer to the start of the header. typedef std::vector<HeaderRef> HeaderList; void Parse(const uint8_t* data, size_t dataLen, HeaderList& headers); };
34.44
129
0.757259
[ "vector" ]
a5e296af33950e2709d4707ff77dafa2036c9e21
1,837
c
C
examples/ordfilt_rrrf_example.c
vankxr/liquid-dsp
cd4d858a00eab6e2ffb88aa36b38a0fb1c741f30
[ "MIT" ]
1,382
2015-01-06T09:41:13.000Z
2022-03-31T18:31:06.000Z
examples/ordfilt_rrrf_example.c
vankxr/liquid-dsp
cd4d858a00eab6e2ffb88aa36b38a0fb1c741f30
[ "MIT" ]
227
2015-02-06T17:04:42.000Z
2022-03-31T06:48:20.000Z
examples/ordfilt_rrrf_example.c
vankxr/liquid-dsp
cd4d858a00eab6e2ffb88aa36b38a0fb1c741f30
[ "MIT" ]
394
2015-01-20T21:56:39.000Z
2022-03-26T12:44:05.000Z
// // ordfilt_rrrf_example.c // #include <stdio.h> #include <math.h> #include "liquid.h" #define OUTPUT_FILENAME "ordfilt_rrrf_example.m" int main() { // options unsigned int num_samples = 2400; // number of random input samples unsigned int n = 101; // filter length unsigned int k = 5; // order statistic index // arrays float x[num_samples]; // filter input float y[num_samples]; // filter output // generate input tone with noise unsigned int i; for (i=0; i<num_samples; i++) x[i] = -cosf(2*M_PI*(float)i/(float)num_samples) + fabsf(randnf()); // create object ordfilt_rrrf q = ordfilt_rrrf_create(n,k); ordfilt_rrrf_print(q); // apply filter ordfilt_rrrf_execute_block(q,x,num_samples,y); // destroy filter object ordfilt_rrrf_destroy(q); // // export results // FILE * fid = fopen(OUTPUT_FILENAME,"w"); fprintf(fid,"%% ordfilt_rrrf_example.m: auto-generated file\n\n"); fprintf(fid,"clear all;\nclose all;\n\n"); fprintf(fid,"num_samples=%u;\n", num_samples); fprintf(fid,"x = zeros(1,num_samples);\n"); fprintf(fid,"y = zeros(1,num_samples);\n"); for (i=0; i<num_samples; i++) fprintf(fid,"x(%4u) = %12.4e; y(%4u) = %12.4e;\n", i+1, x[i], i+1, y[i]); fprintf(fid,"t = 0:(num_samples-1);\n"); fprintf(fid,"figure;\n"); fprintf(fid,"plot(t,x,'Color',[0.3 0.3 0.3],...\n"); fprintf(fid," t,y,'LineWidth',2);\n"); fprintf(fid,"grid on;\n"); fprintf(fid,"xlabel('time');\n"); fprintf(fid,"ylabel('signals');\n"); fprintf(fid,"axis([0 num_samples -4 4]);\n"); fprintf(fid,"legend('noise','filtered noise',1);"); fclose(fid); printf("results written to %s\n", OUTPUT_FILENAME); printf("done.\n"); return 0; }
27.41791
81
0.595536
[ "object" ]
a5e75c4b929c083698c1af1825629e088c407a8e
4,142
h
C
src/rendering/shader.h
ZetaGlest/3DEngineCpp
a9264241bfa553ca1dde0277391c6c7e69854f26
[ "Apache-2.0" ]
252
2015-01-04T20:39:03.000Z
2022-03-31T15:14:06.000Z
src/rendering/shader.h
ZetaGlest/3DEngineCpp
a9264241bfa553ca1dde0277391c6c7e69854f26
[ "Apache-2.0" ]
19
2015-01-21T14:52:04.000Z
2022-01-28T13:18:14.000Z
src/rendering/shader.h
ZetaGlest/3DEngineCpp
a9264241bfa553ca1dde0277391c6c7e69854f26
[ "Apache-2.0" ]
98
2015-01-09T04:08:27.000Z
2022-02-16T07:44:09.000Z
/* * Copyright (C) 2014 Benny Bobaganoosh * * 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 SHADER_H #define SHADER_H #include <map> #include <vector> #include <string> #include "../core/referenceCounter.h" #include "../core/math3d.h" #include "../core/transform.h" #include "material.h" #include "camera.h" class RenderingEngine; class DirectionalLight; class PointLight; class SpotLight; class TypedData { public: TypedData(const std::string& name, const std::string& type) : m_name(name), m_type(type) {} inline const std::string& GetName() const { return m_name; } inline const std::string& GetType() const { return m_type; } private: std::string m_name; std::string m_type; }; class UniformStruct { public: UniformStruct(const std::string& name, const std::vector<TypedData>& memberNames) : m_name(name), m_memberNames(memberNames) {} inline const std::string& GetName() const { return m_name; } inline const std::vector<TypedData>& GetMemberNames() const { return m_memberNames; } private: std::string m_name; std::vector<TypedData> m_memberNames; }; class ShaderData : public ReferenceCounter { public: ShaderData(const std::string& fileName); virtual ~ShaderData(); inline int GetProgram() const { return m_program; } inline const std::vector<int>& GetShaders() const { return m_shaders; } inline const std::vector<std::string>& GetUniformNames() const { return m_uniformNames; } inline const std::vector<std::string>& GetUniformTypes() const { return m_uniformTypes; } inline const std::map<std::string, unsigned int>& GetUniformMap() const { return m_uniformMap; } private: void AddVertexShader(const std::string& text); void AddGeometryShader(const std::string& text); void AddFragmentShader(const std::string& text); void AddProgram(const std::string& text, int type); void AddAllAttributes(const std::string& vertexShaderText, const std::string& attributeKeyword); void AddShaderUniforms(const std::string& shaderText); void AddUniform(const std::string& uniformName, const std::string& uniformType, const std::vector<UniformStruct>& structs); void CompileShader() const; static int s_supportedOpenGLLevel; static std::string s_glslVersion; int m_program; std::vector<int> m_shaders; std::vector<std::string> m_uniformNames; std::vector<std::string> m_uniformTypes; std::map<std::string, unsigned int> m_uniformMap; }; class Shader { public: Shader(const std::string& fileName = "basicShader"); Shader(const Shader& other); virtual ~Shader(); void Bind() const; virtual void UpdateUniforms(const Transform& transform, const Material& material, const RenderingEngine& renderingEngine, const Camera& camera) const; void SetUniformi(const std::string& uniformName, int value) const; void SetUniformf(const std::string& uniformName, float value) const; void SetUniformMatrix4f(const std::string& uniformName, const Matrix4f& value) const; void SetUniformVector3f(const std::string& uniformName, const Vector3f& value) const; protected: private: static std::map<std::string, ShaderData*> s_resourceMap; ShaderData* m_shaderData; std::string m_fileName; void SetUniformDirectionalLight(const std::string& uniformName, const DirectionalLight& value) const; void SetUniformPointLight(const std::string& uniformName, const PointLight& value) const; void SetUniformSpotLight(const std::string& uniformName, const SpotLight& value) const; void operator=(const Shader& other) {} }; #endif
33.674797
151
0.727426
[ "vector", "transform" ]
a5fd6d1aac483c8ba049c143fbfd0c0c6c6b2981
15,957
h
C
aws-cpp-sdk-alexaforbusiness/include/aws/alexaforbusiness/model/UpdateProfileRequest.h
MajorMurphy/aws-sdk-cpp
e116ae4f91ffe9c22ad5b1854b4cd8970eaf9b4b
[ "Apache-2.0" ]
1
2019-10-10T20:58:44.000Z
2019-10-10T20:58:44.000Z
aws-cpp-sdk-alexaforbusiness/include/aws/alexaforbusiness/model/UpdateProfileRequest.h
MajorMurphy/aws-sdk-cpp
e116ae4f91ffe9c22ad5b1854b4cd8970eaf9b4b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-alexaforbusiness/include/aws/alexaforbusiness/model/UpdateProfileRequest.h
MajorMurphy/aws-sdk-cpp
e116ae4f91ffe9c22ad5b1854b4cd8970eaf9b4b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/alexaforbusiness/AlexaForBusiness_EXPORTS.h> #include <aws/alexaforbusiness/AlexaForBusinessRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/alexaforbusiness/model/DistanceUnit.h> #include <aws/alexaforbusiness/model/TemperatureUnit.h> #include <aws/alexaforbusiness/model/WakeWord.h> #include <utility> namespace Aws { namespace AlexaForBusiness { namespace Model { /** */ class AWS_ALEXAFORBUSINESS_API UpdateProfileRequest : public AlexaForBusinessRequest { public: UpdateProfileRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "UpdateProfile"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The ARN of the room profile to update. Required.</p> */ inline const Aws::String& GetProfileArn() const{ return m_profileArn; } /** * <p>The ARN of the room profile to update. Required.</p> */ inline bool ProfileArnHasBeenSet() const { return m_profileArnHasBeenSet; } /** * <p>The ARN of the room profile to update. Required.</p> */ inline void SetProfileArn(const Aws::String& value) { m_profileArnHasBeenSet = true; m_profileArn = value; } /** * <p>The ARN of the room profile to update. Required.</p> */ inline void SetProfileArn(Aws::String&& value) { m_profileArnHasBeenSet = true; m_profileArn = std::move(value); } /** * <p>The ARN of the room profile to update. Required.</p> */ inline void SetProfileArn(const char* value) { m_profileArnHasBeenSet = true; m_profileArn.assign(value); } /** * <p>The ARN of the room profile to update. Required.</p> */ inline UpdateProfileRequest& WithProfileArn(const Aws::String& value) { SetProfileArn(value); return *this;} /** * <p>The ARN of the room profile to update. Required.</p> */ inline UpdateProfileRequest& WithProfileArn(Aws::String&& value) { SetProfileArn(std::move(value)); return *this;} /** * <p>The ARN of the room profile to update. Required.</p> */ inline UpdateProfileRequest& WithProfileArn(const char* value) { SetProfileArn(value); return *this;} /** * <p>The updated name for the room profile.</p> */ inline const Aws::String& GetProfileName() const{ return m_profileName; } /** * <p>The updated name for the room profile.</p> */ inline bool ProfileNameHasBeenSet() const { return m_profileNameHasBeenSet; } /** * <p>The updated name for the room profile.</p> */ inline void SetProfileName(const Aws::String& value) { m_profileNameHasBeenSet = true; m_profileName = value; } /** * <p>The updated name for the room profile.</p> */ inline void SetProfileName(Aws::String&& value) { m_profileNameHasBeenSet = true; m_profileName = std::move(value); } /** * <p>The updated name for the room profile.</p> */ inline void SetProfileName(const char* value) { m_profileNameHasBeenSet = true; m_profileName.assign(value); } /** * <p>The updated name for the room profile.</p> */ inline UpdateProfileRequest& WithProfileName(const Aws::String& value) { SetProfileName(value); return *this;} /** * <p>The updated name for the room profile.</p> */ inline UpdateProfileRequest& WithProfileName(Aws::String&& value) { SetProfileName(std::move(value)); return *this;} /** * <p>The updated name for the room profile.</p> */ inline UpdateProfileRequest& WithProfileName(const char* value) { SetProfileName(value); return *this;} /** * <p>Sets the profile as default if selected. If this is missing, no update is * done to the default status.</p> */ inline bool GetIsDefault() const{ return m_isDefault; } /** * <p>Sets the profile as default if selected. If this is missing, no update is * done to the default status.</p> */ inline bool IsDefaultHasBeenSet() const { return m_isDefaultHasBeenSet; } /** * <p>Sets the profile as default if selected. If this is missing, no update is * done to the default status.</p> */ inline void SetIsDefault(bool value) { m_isDefaultHasBeenSet = true; m_isDefault = value; } /** * <p>Sets the profile as default if selected. If this is missing, no update is * done to the default status.</p> */ inline UpdateProfileRequest& WithIsDefault(bool value) { SetIsDefault(value); return *this;} /** * <p>The updated timezone for the room profile.</p> */ inline const Aws::String& GetTimezone() const{ return m_timezone; } /** * <p>The updated timezone for the room profile.</p> */ inline bool TimezoneHasBeenSet() const { return m_timezoneHasBeenSet; } /** * <p>The updated timezone for the room profile.</p> */ inline void SetTimezone(const Aws::String& value) { m_timezoneHasBeenSet = true; m_timezone = value; } /** * <p>The updated timezone for the room profile.</p> */ inline void SetTimezone(Aws::String&& value) { m_timezoneHasBeenSet = true; m_timezone = std::move(value); } /** * <p>The updated timezone for the room profile.</p> */ inline void SetTimezone(const char* value) { m_timezoneHasBeenSet = true; m_timezone.assign(value); } /** * <p>The updated timezone for the room profile.</p> */ inline UpdateProfileRequest& WithTimezone(const Aws::String& value) { SetTimezone(value); return *this;} /** * <p>The updated timezone for the room profile.</p> */ inline UpdateProfileRequest& WithTimezone(Aws::String&& value) { SetTimezone(std::move(value)); return *this;} /** * <p>The updated timezone for the room profile.</p> */ inline UpdateProfileRequest& WithTimezone(const char* value) { SetTimezone(value); return *this;} /** * <p>The updated address for the room profile.</p> */ inline const Aws::String& GetAddress() const{ return m_address; } /** * <p>The updated address for the room profile.</p> */ inline bool AddressHasBeenSet() const { return m_addressHasBeenSet; } /** * <p>The updated address for the room profile.</p> */ inline void SetAddress(const Aws::String& value) { m_addressHasBeenSet = true; m_address = value; } /** * <p>The updated address for the room profile.</p> */ inline void SetAddress(Aws::String&& value) { m_addressHasBeenSet = true; m_address = std::move(value); } /** * <p>The updated address for the room profile.</p> */ inline void SetAddress(const char* value) { m_addressHasBeenSet = true; m_address.assign(value); } /** * <p>The updated address for the room profile.</p> */ inline UpdateProfileRequest& WithAddress(const Aws::String& value) { SetAddress(value); return *this;} /** * <p>The updated address for the room profile.</p> */ inline UpdateProfileRequest& WithAddress(Aws::String&& value) { SetAddress(std::move(value)); return *this;} /** * <p>The updated address for the room profile.</p> */ inline UpdateProfileRequest& WithAddress(const char* value) { SetAddress(value); return *this;} /** * <p>The updated distance unit for the room profile.</p> */ inline const DistanceUnit& GetDistanceUnit() const{ return m_distanceUnit; } /** * <p>The updated distance unit for the room profile.</p> */ inline bool DistanceUnitHasBeenSet() const { return m_distanceUnitHasBeenSet; } /** * <p>The updated distance unit for the room profile.</p> */ inline void SetDistanceUnit(const DistanceUnit& value) { m_distanceUnitHasBeenSet = true; m_distanceUnit = value; } /** * <p>The updated distance unit for the room profile.</p> */ inline void SetDistanceUnit(DistanceUnit&& value) { m_distanceUnitHasBeenSet = true; m_distanceUnit = std::move(value); } /** * <p>The updated distance unit for the room profile.</p> */ inline UpdateProfileRequest& WithDistanceUnit(const DistanceUnit& value) { SetDistanceUnit(value); return *this;} /** * <p>The updated distance unit for the room profile.</p> */ inline UpdateProfileRequest& WithDistanceUnit(DistanceUnit&& value) { SetDistanceUnit(std::move(value)); return *this;} /** * <p>The updated temperature unit for the room profile.</p> */ inline const TemperatureUnit& GetTemperatureUnit() const{ return m_temperatureUnit; } /** * <p>The updated temperature unit for the room profile.</p> */ inline bool TemperatureUnitHasBeenSet() const { return m_temperatureUnitHasBeenSet; } /** * <p>The updated temperature unit for the room profile.</p> */ inline void SetTemperatureUnit(const TemperatureUnit& value) { m_temperatureUnitHasBeenSet = true; m_temperatureUnit = value; } /** * <p>The updated temperature unit for the room profile.</p> */ inline void SetTemperatureUnit(TemperatureUnit&& value) { m_temperatureUnitHasBeenSet = true; m_temperatureUnit = std::move(value); } /** * <p>The updated temperature unit for the room profile.</p> */ inline UpdateProfileRequest& WithTemperatureUnit(const TemperatureUnit& value) { SetTemperatureUnit(value); return *this;} /** * <p>The updated temperature unit for the room profile.</p> */ inline UpdateProfileRequest& WithTemperatureUnit(TemperatureUnit&& value) { SetTemperatureUnit(std::move(value)); return *this;} /** * <p>The updated wake word for the room profile.</p> */ inline const WakeWord& GetWakeWord() const{ return m_wakeWord; } /** * <p>The updated wake word for the room profile.</p> */ inline bool WakeWordHasBeenSet() const { return m_wakeWordHasBeenSet; } /** * <p>The updated wake word for the room profile.</p> */ inline void SetWakeWord(const WakeWord& value) { m_wakeWordHasBeenSet = true; m_wakeWord = value; } /** * <p>The updated wake word for the room profile.</p> */ inline void SetWakeWord(WakeWord&& value) { m_wakeWordHasBeenSet = true; m_wakeWord = std::move(value); } /** * <p>The updated wake word for the room profile.</p> */ inline UpdateProfileRequest& WithWakeWord(const WakeWord& value) { SetWakeWord(value); return *this;} /** * <p>The updated wake word for the room profile.</p> */ inline UpdateProfileRequest& WithWakeWord(WakeWord&& value) { SetWakeWord(std::move(value)); return *this;} /** * <p>The updated locale for the room profile.</p> */ inline const Aws::String& GetLocale() const{ return m_locale; } /** * <p>The updated locale for the room profile.</p> */ inline bool LocaleHasBeenSet() const { return m_localeHasBeenSet; } /** * <p>The updated locale for the room profile.</p> */ inline void SetLocale(const Aws::String& value) { m_localeHasBeenSet = true; m_locale = value; } /** * <p>The updated locale for the room profile.</p> */ inline void SetLocale(Aws::String&& value) { m_localeHasBeenSet = true; m_locale = std::move(value); } /** * <p>The updated locale for the room profile.</p> */ inline void SetLocale(const char* value) { m_localeHasBeenSet = true; m_locale.assign(value); } /** * <p>The updated locale for the room profile.</p> */ inline UpdateProfileRequest& WithLocale(const Aws::String& value) { SetLocale(value); return *this;} /** * <p>The updated locale for the room profile.</p> */ inline UpdateProfileRequest& WithLocale(Aws::String&& value) { SetLocale(std::move(value)); return *this;} /** * <p>The updated locale for the room profile.</p> */ inline UpdateProfileRequest& WithLocale(const char* value) { SetLocale(value); return *this;} /** * <p>Whether the setup mode of the profile is enabled.</p> */ inline bool GetSetupModeDisabled() const{ return m_setupModeDisabled; } /** * <p>Whether the setup mode of the profile is enabled.</p> */ inline bool SetupModeDisabledHasBeenSet() const { return m_setupModeDisabledHasBeenSet; } /** * <p>Whether the setup mode of the profile is enabled.</p> */ inline void SetSetupModeDisabled(bool value) { m_setupModeDisabledHasBeenSet = true; m_setupModeDisabled = value; } /** * <p>Whether the setup mode of the profile is enabled.</p> */ inline UpdateProfileRequest& WithSetupModeDisabled(bool value) { SetSetupModeDisabled(value); return *this;} /** * <p>The updated maximum volume limit for the room profile.</p> */ inline int GetMaxVolumeLimit() const{ return m_maxVolumeLimit; } /** * <p>The updated maximum volume limit for the room profile.</p> */ inline bool MaxVolumeLimitHasBeenSet() const { return m_maxVolumeLimitHasBeenSet; } /** * <p>The updated maximum volume limit for the room profile.</p> */ inline void SetMaxVolumeLimit(int value) { m_maxVolumeLimitHasBeenSet = true; m_maxVolumeLimit = value; } /** * <p>The updated maximum volume limit for the room profile.</p> */ inline UpdateProfileRequest& WithMaxVolumeLimit(int value) { SetMaxVolumeLimit(value); return *this;} /** * <p>Whether the PSTN setting of the room profile is enabled.</p> */ inline bool GetPSTNEnabled() const{ return m_pSTNEnabled; } /** * <p>Whether the PSTN setting of the room profile is enabled.</p> */ inline bool PSTNEnabledHasBeenSet() const { return m_pSTNEnabledHasBeenSet; } /** * <p>Whether the PSTN setting of the room profile is enabled.</p> */ inline void SetPSTNEnabled(bool value) { m_pSTNEnabledHasBeenSet = true; m_pSTNEnabled = value; } /** * <p>Whether the PSTN setting of the room profile is enabled.</p> */ inline UpdateProfileRequest& WithPSTNEnabled(bool value) { SetPSTNEnabled(value); return *this;} private: Aws::String m_profileArn; bool m_profileArnHasBeenSet; Aws::String m_profileName; bool m_profileNameHasBeenSet; bool m_isDefault; bool m_isDefaultHasBeenSet; Aws::String m_timezone; bool m_timezoneHasBeenSet; Aws::String m_address; bool m_addressHasBeenSet; DistanceUnit m_distanceUnit; bool m_distanceUnitHasBeenSet; TemperatureUnit m_temperatureUnit; bool m_temperatureUnitHasBeenSet; WakeWord m_wakeWord; bool m_wakeWordHasBeenSet; Aws::String m_locale; bool m_localeHasBeenSet; bool m_setupModeDisabled; bool m_setupModeDisabledHasBeenSet; int m_maxVolumeLimit; bool m_maxVolumeLimitHasBeenSet; bool m_pSTNEnabled; bool m_pSTNEnabledHasBeenSet; }; } // namespace Model } // namespace AlexaForBusiness } // namespace Aws
33.45283
137
0.668547
[ "model" ]
5704771b85e61d0647c93a8af93172eb0e0a14fc
8,169
h
C
src/net/pspnet_adhocmatching.h
tecgen/pspsdk
b02372847905b8c44ec1ac59920e8fc69e8517b0
[ "BSD-3-Clause" ]
1
2017-11-24T02:35:52.000Z
2017-11-24T02:35:52.000Z
src/net/pspnet_adhocmatching.h
tecgen/pspsdk
b02372847905b8c44ec1ac59920e8fc69e8517b0
[ "BSD-3-Clause" ]
null
null
null
src/net/pspnet_adhocmatching.h
tecgen/pspsdk
b02372847905b8c44ec1ac59920e8fc69e8517b0
[ "BSD-3-Clause" ]
1
2019-12-26T03:57:11.000Z
2019-12-26T03:57:11.000Z
/* * PSP Software Development Kit - http://www.pspdev.org * ----------------------------------------------------------------------- * Licensed under the BSD license, see LICENSE in PSPSDK root for details. * * pspnet_adhocmatching.h - PSP Adhoc matching networking libraries. * * Copyright (c) 2006 James F. * Copyright (c) 2008 InsertWittyName <tias_dp@hotmail.com> * * Based on the adhoc code in SMS Plus * * $Id: pspnet_adhocmatching.h 2433 2008-10-15 10:00:27Z iwn $ */ #ifndef __PSPNETMATCHING_ADHOC_H__ #define __PSPNETMATCHING_ADHOC_H__ #ifdef __cplusplus extern "C" { #endif /** * Matching events used in pspAdhocMatchingCallback */ enum pspAdhocMatchingEvents { /** Hello event. optdata contains data if optlen > 0. */ PSP_ADHOC_MATCHING_EVENT_HELLO = 1, /** Join request. optdata contains data if optlen > 0. */ PSP_ADHOC_MATCHING_EVENT_JOIN = 2, /** Target left matching. */ PSP_ADHOC_MATCHING_EVENT_LEFT = 3, /** Join request rejected. */ PSP_ADHOC_MATCHING_EVENT_REJECT = 4, /** Join request cancelled. */ PSP_ADHOC_MATCHING_EVENT_CANCEL = 5, /** Join request accepted. optdata contains data if optlen > 0. */ PSP_ADHOC_MATCHING_EVENT_ACCEPT = 6, /** Matching is complete. */ PSP_ADHOC_MATCHING_EVENT_COMPLETE = 7, /** Ping timeout event. */ PSP_ADHOC_MATCHING_EVENT_TIMEOUT = 8, /** Error event. */ PSP_ADHOC_MATCHING_EVENT_ERROR = 9, /** Peer disconnect event. */ PSP_ADHOC_MATCHING_EVENT_DISCONNECT = 10, /** Data received event. optdata contains data if optlen > 0. */ PSP_ADHOC_MATCHING_EVENT_DATA = 11, /** Data acknowledged event. */ PSP_ADHOC_MATCHING_EVENT_DATA_CONFIRM = 12, /** Data timeout event. */ PSP_ADHOC_MATCHING_EVENT_DATA_TIMEOUT = 13 }; /** * Matching modes used in sceNetAdhocMatchingCreate */ enum pspAdhocMatchingModes { /** Host */ PSP_ADHOC_MATCHING_MODE_HOST = 1, /** Client */ PSP_ADHOC_MATCHING_MODE_CLIENT = 2, /** Peer to peer */ PSP_ADHOC_MATCHING_MODE_PTP = 3 }; /** * Linked list for sceNetAdhocMatchingGetMembers */ struct pspAdhocMatchingMember { struct pspAdhocMatchingMember *next; unsigned char mac[6]; char unknown[2]; }; /** * Linked list for sceNetAdhocMatchingGetMembers */ struct pspAdhocPoolStat { /** Size of the pool */ int size; /** Maximum size of the pool */ int maxsize; /** Unused memory in the pool */ int freesize; }; /** * Initialise the Adhoc matching library * * @param memsize - Internal memory pool size. Lumines uses 0x20000 * * @return 0 on success, < 0 on error */ int sceNetAdhocMatchingInit(int memsize); /** * Terminate the Adhoc matching library * * @return 0 on success, < 0 on error */ int sceNetAdhocMatchingTerm(void); /** Matching callback */ typedef void (*pspAdhocMatchingCallback)(int matchingid, int event, unsigned char *mac, int optlen, void *optdata); /** * Create an Adhoc matching object * * @param mode - One of ::pspAdhocMatchingModes * @param maxpeers - Maximum number of peers to match (only used when mode is PSP_ADHOC_MATCHING_MODE_HOST) * @param port - Port. Lumines uses 0x22B * @param bufsize - Receiving buffer size * @param hellodelay - Hello message send delay in microseconds (only used when mode is PSP_ADHOC_MATCHING_MODE_HOST or PSP_ADHOC_MATCHING_MODE_PTP) * @param pingdelay - Ping send delay in microseconds. Lumines uses 0x5B8D80 (only used when mode is PSP_ADHOC_MATCHING_MODE_HOST or PSP_ADHOC_MATCHING_MODE_PTP) * @param initcount - Initial count of the of the resend counter. Lumines uses 3 * @param msgdelay - Message send delay in microseconds * @param callback - Callback to be called for matching * * @return ID of object on success, < 0 on error. */ int sceNetAdhocMatchingCreate(int mode, int maxpeers, unsigned short port, int bufsize, unsigned int hellodelay, unsigned int pingdelay, int initcount, unsigned int msgdelay, pspAdhocMatchingCallback callback); /** * Delete an Adhoc matching object * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingDelete(int matchingid); /** * Start a matching object * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param evthpri - Priority of the event handler thread. Lumines uses 0x10 * @param evthstack - Stack size of the event handler thread. Lumines uses 0x2000 * @param inthpri - Priority of the input handler thread. Lumines uses 0x10 * @param inthstack - Stack size of the input handler thread. Lumines uses 0x2000 * @param optlen - Size of hellodata * @param optdata - Pointer to block of data passed to callback * * @return 0 on success, < 0 on error */ int sceNetAdhocMatchingStart(int matchingid, int evthpri, int evthstack, int inthpri, int inthstack, int optlen, void *optdata); /** * Stop a matching object * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingStop(int matchingid); /** * Select a matching target * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param mac - MAC address to select * @param optlen - Optional data length * @param optdata - Pointer to the optional data * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingSelectTarget(int matchingid, unsigned char *mac, int optlen, void *optdata); /** * Cancel a matching target * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param mac - The MAC address to cancel * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingCancelTarget(int matchingid, unsigned char *mac); /** * Cancel a matching target (with optional data) * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param mac - The MAC address to cancel * @param optlen - Optional data length * @param optdata - Pointer to the optional data * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingCancelTargetWithOpt(int matchingid, unsigned char *mac, int optlen, void *optdata); /** * Send data to a matching target * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param mac - The MAC address to send the data to * @param datalen - Length of the data * @param data - Pointer to the data * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingSendData(int matchingid, unsigned char *mac, int datalen, void *data); /** * Abort a data send to a matching target * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param mac - The MAC address to send the data to * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingAbortSendData(int matchingid, unsigned char *mac); /** * Set the optional hello message * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param optlen - Length of the hello data * @param optdata - Pointer to the hello data * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingSetHelloOpt(int matchingid, int optlen, void *optdata); /** * Get the optional hello message * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param optlen - Length of the hello data * @param optdata - Pointer to the hello data * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingGetHelloOpt(int matchingid, int *optlen, void *optdata); /** * Get a list of matching members * * @param matchingid - The ID returned from ::sceNetAdhocMatchingCreate * @param length - The length of the list. * @param buf - An allocated area of size length. * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingGetMembers(int matchingid, int *length, void *buf); /** * Get the maximum memory usage by the matching library * * @return The memory usage on success, < 0 on error. */ int sceNetAdhocMatchingGetPoolMaxAlloc(void); /** * Get the status of the memory pool used by the matching library * * @param poolstat - A ::pspAdhocPoolStat. * * @return 0 on success, < 0 on error. */ int sceNetAdhocMatchingGetPoolStat(struct pspAdhocPoolStat *poolstat); #ifdef __cplusplus } #endif #endif
30.255556
210
0.723222
[ "object" ]
570897ca9f48e4590f4e356fcbe91c7841cd8732
997
h
C
HIJSONModel/HIObjectManager.h
shkimturf/HIJSONModel
4328ef7b82deae7ae08ca3d7491ad8107a20cee1
[ "MIT" ]
null
null
null
HIJSONModel/HIObjectManager.h
shkimturf/HIJSONModel
4328ef7b82deae7ae08ca3d7491ad8107a20cee1
[ "MIT" ]
null
null
null
HIJSONModel/HIObjectManager.h
shkimturf/HIJSONModel
4328ef7b82deae7ae08ca3d7491ad8107a20cee1
[ "MIT" ]
null
null
null
// // HIObjectManager.h // HIDevKit // // Created by Sunhong Kim on 2014. 9. 16.. // Copyright (c) 2014년 Sunhong Kim. All rights reserved. // #import <Foundation/Foundation.h> #import "HIObject.h" #import "HIObjectObserver.h" @interface HIObjectManager : NSObject { NSMutableDictionary* _objectCache; NSMutableDictionary* _objectObservers; } @property (atomic, strong, readonly) NSDictionary* objectCache; @property (atomic, strong, readonly) NSDictionary* objectObservers; - (HIObject*)getObjectFromCacheByID:(NSString*)iid; /* * Supporting functions to observe object updating * - Don't forget call removeObserver: in dealloc function */ - (void)addObserver:(id<HIObjectObserver>)observer forObjectID:(NSString*)objectID; - (void)removeObserver:(id<HIObjectObserver>)observer forObjectID:(NSString*)objectID; - (void)removeObserver:(id<HIObjectObserver>)observer; /* * Notice a object updated by other request. */ - (void)onObjectUpdated:(HIObject*)object; @end
24.925
86
0.746239
[ "object" ]
02110d631fb4def572d8c49c662d4df77d9c233f
1,596
h
C
paddle/phi/kernels/impl/unsqueeze_kernel_impl.h
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/phi/kernels/impl/unsqueeze_kernel_impl.h
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
null
null
null
paddle/phi/kernels/impl/unsqueeze_kernel_impl.h
RangeKing/Paddle
2d87300809ae75d76f5b0b457d8112cb88dc3e27
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
// Copyright (c) 2022 PaddlePaddle Authors. 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. #pragma once #include "paddle/phi/core/dense_tensor.h" #include "paddle/phi/kernels/copy_kernel.h" #include "paddle/phi/kernels/funcs/unsqueeze.h" namespace phi { template <typename T, typename Context> void UnsqueezeKernel(const Context& dev_ctx, const DenseTensor& x, const IntArray& axes, DenseTensor* out, DenseTensor* xshape) { auto x_dims = x.dims(); auto out_dims = out->dims(); if (axes.FromTensor()) { std::vector<int32_t> tmp; tmp.reserve(axes.GetData().size()); std::for_each(axes.GetData().begin(), axes.GetData().end(), [&tmp](const int64_t& t) { tmp.push_back(t); }); out_dims = funcs::GetUnsqueezeShape(tmp, x_dims); } out->Resize(out_dims); dev_ctx.template Alloc<T>(out); phi::Copy(dev_ctx, x, dev_ctx.GetPlace(), false, out); out->Resize(out_dims); // copy will reset the dims. } } // namespace phi
37.116279
75
0.66416
[ "vector" ]
02143fa2fd5b8e08b47ca8b12891a7661c81f7be
7,365
h
C
remoting/host/chromoting_host.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
remoting/host/chromoting_host.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
remoting/host/chromoting_host.h
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 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 REMOTING_CHROMOTING_HOST_H_ #define REMOTING_CHROMOTING_HOST_H_ #include <string> #include "base/memory/scoped_ptr.h" #include "base/threading/thread.h" #include "remoting/base/encoder.h" #include "remoting/host/access_verifier.h" #include "remoting/host/capturer.h" #include "remoting/host/client_session.h" #include "remoting/host/desktop_environment.h" #include "remoting/host/heartbeat_sender.h" #include "remoting/jingle_glue/jingle_client.h" #include "remoting/jingle_glue/jingle_thread.h" #include "remoting/protocol/session_manager.h" #include "remoting/protocol/connection_to_client.h" class Task; namespace remoting { namespace protocol { class ConnectionToClient; class HostStub; class InputStub; class SessionConfig; class CandidateSessionConfig; } // namespace protocol class Capturer; class ChromotingHostContext; class DesktopEnvironment; class Encoder; class MutableHostConfig; class ScreenRecorder; // A class to implement the functionality of a host process. // // Here's the work flow of this class: // 1. We should load the saved GAIA ID token or if this is the first // time the host process runs we should prompt user for the // credential. We will use this token or credentials to authenicate // and register the host. // // 2. We listen for incoming connection using libjingle. We will create // a ConnectionToClient object that wraps around linjingle for transport. // A ScreenRecorder is created with an Encoder and a Capturer. // A ConnectionToClient is added to the ScreenRecorder for transporting // the screen captures. An InputStub is created and registered with the // ConnectionToClient to receive mouse / keyboard events from the remote // client. // After we have done all the initialization we'll start the ScreenRecorder. // We'll then enter the running state of the host process. // // 3. When the user is disconnected, we will pause the ScreenRecorder // and try to terminate the threads we have created. This will allow // all pending tasks to complete. After all of that completed we // return to the idle state. We then go to step (2) if there a new // incoming connection. class ChromotingHost : public base::RefCountedThreadSafe<ChromotingHost>, public protocol::ConnectionToClient::EventHandler, public ClientSession::EventHandler, public JingleClient::Callback { public: // Factory methods that must be used to create ChromotingHost instances. // Default capturer and input stub are used if it is not specified. static ChromotingHost* Create(ChromotingHostContext* context, MutableHostConfig* config); static ChromotingHost* Create(ChromotingHostContext* context, MutableHostConfig* config, DesktopEnvironment* environment); // Asynchronously start the host process. // // After this is invoked, the host process will connect to the talk // network and start listening for incoming connections. // // |shutdown_task| is called if Start() has failed ot Shutdown() is called // and all related operations are completed. // // This method can only be called once during the lifetime of this object. void Start(Task* shutdown_task); // Asynchronously shutdown the host process. void Shutdown(); // This method is called if a client is connected to this object. void OnClientConnected(protocol::ConnectionToClient* client); // This method is called if a client is disconnected from the host. void OnClientDisconnected(protocol::ConnectionToClient* client); //////////////////////////////////////////////////////////////////////////// // protocol::ConnectionToClient::EventHandler implementations virtual void OnConnectionOpened(protocol::ConnectionToClient* client); virtual void OnConnectionClosed(protocol::ConnectionToClient* client); virtual void OnConnectionFailed(protocol::ConnectionToClient* client); //////////////////////////////////////////////////////////////////////////// // JingleClient::Callback implementations virtual void OnStateChange(JingleClient* client, JingleClient::State state); //////////////////////////////////////////////////////////////////////////// // ClientSession::EventHandler implementations virtual void LocalLoginSucceeded( scoped_refptr<protocol::ConnectionToClient> client); virtual void LocalLoginFailed( scoped_refptr<protocol::ConnectionToClient> client); // Callback for ChromotingServer. void OnNewClientSession( protocol::Session* session, protocol::SessionManager::IncomingSessionResponse* response); // Sets desired configuration for the protocol. Ownership of the // |config| is transferred to the object. Must be called before Start(). void set_protocol_config(protocol::CandidateSessionConfig* config); // This setter is only used in unit test to simulate client connection. void AddClient(ClientSession* client); private: friend class base::RefCountedThreadSafe<ChromotingHost>; ChromotingHost(ChromotingHostContext* context, MutableHostConfig* config, DesktopEnvironment* environment); virtual ~ChromotingHost(); enum State { kInitial, kStarted, kStopped, }; // Callback for protocol::SessionManager::Close(). void OnServerClosed(); // Creates encoder for the specified configuration. Encoder* CreateEncoder(const protocol::SessionConfig* config); std::string GenerateHostAuthToken(const std::string& encoded_client_token); bool HasAuthenticatedClients() const; void EnableCurtainMode(bool enable); // The context that the chromoting host runs on. ChromotingHostContext* context_; scoped_refptr<MutableHostConfig> config_; scoped_ptr<DesktopEnvironment> desktop_environment_; scoped_ptr<SignalStrategy> signal_strategy_; // The libjingle client. This is used to connect to the talk network to // receive connection requests from chromoting client. scoped_refptr<JingleClient> jingle_client_; scoped_refptr<protocol::SessionManager> session_manager_; // Objects that takes care of sending heartbeats to the chromoting bot. scoped_refptr<HeartbeatSender> heartbeat_sender_; AccessVerifier access_verifier_; // The connections to remote clients. std::vector<scoped_refptr<ClientSession> > clients_; // Session manager for the host process. scoped_refptr<ScreenRecorder> recorder_; // This task gets executed when this object fails to connect to the // talk network or Shutdown() is called. scoped_ptr<Task> shutdown_task_; // Tracks the internal state of the host. // This variable is written on the main thread of ChromotingHostContext // and read by jingle thread. State state_; // Lock is to lock the access to |state_|. base::Lock lock_; // Configuration of the protocol. scoped_ptr<protocol::CandidateSessionConfig> protocol_config_; // Whether or not the host is currently curtained. bool is_curtained_; DISALLOW_COPY_AND_ASSIGN(ChromotingHost); }; } // namespace remoting #endif // REMOTING_HOST_CHROMOTING_HOST_H_
36.460396
79
0.72926
[ "object", "vector" ]
02199e2b715042364e4b2160daf762e1b7b8a78c
1,183
c
C
unix-x86/tests/adler32_test.c
mazoti/adler32
a7d27786344277a6fe589ba98c0210d96c88fc8e
[ "BSD-3-Clause" ]
null
null
null
unix-x86/tests/adler32_test.c
mazoti/adler32
a7d27786344277a6fe589ba98c0210d96c88fc8e
[ "BSD-3-Clause" ]
null
null
null
unix-x86/tests/adler32_test.c
mazoti/adler32
a7d27786344277a6fe589ba98c0210d96c88fc8e
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <time.h> #include <stdint.h> int adler32(unsigned char* buffer, int len); typedef struct { const char* input; size_t inputSize; uint32_t result; } unit_test; static const unit_test tests[] = { {"", 0, 0x00000001}, {"a", 1, 0x00620062}, {"ab", 2, 0x012600c4}, {"How can you write a big system without C++? -Paul Glick", 56, 0x2e5d1316} }; int main(int argc, char** argv){ time_t start, end; long int fsize; FILE* fp; size_t i, j, testsNumber = sizeof(tests) / sizeof(unit_test); /* get object file by command line argument */ if(argc != 2) { printf("\nERROR: argv[1] missing\n"); return 1; } time(&start); for(j=0; j < 10000; ++j){ for(i=0; i < testsNumber; ++i){ if(adler32((unsigned char*)tests[i].input, tests[i].inputSize) != tests[i].result) { fprintf(stderr , "\n\nTest #%zd => FAIL\n" , i+1); continue; } printf("\nTest #%zd => ok", i+1); } } time(&end); /* get object file size */ fp = fopen(argv[1], "rb"); fseek(fp, 0, SEEK_END); fsize = ftell(fp); fclose(fp); printf("\n\n%s size: %ld bytes", argv[1], fsize); printf("\nelapsed: %.f seconds\n", difftime(end, start)); return 0; }
20.050847
87
0.612849
[ "object" ]