repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
typesAreSpaces/AXDInterpolator
include/Preprocess.h
<reponame>typesAreSpaces/AXDInterpolator<gh_stars>0 #ifndef _PREPROCESS_ #define _PREPROCESS_ #define _DEBUG_PREPROCESS_ 0 #include <iostream> #include <string> #include "AXDSignature.h" class Preprocessor { friend class AXDInterpolant; enum SideInterpolant { PART_A, PART_B }; // [NOTICE] This structure only contains // array vars of different // parametrized types public: class ArrayVars { friend class AXDInterpolant; typedef std::map< unsigned, AXDSignature::z3_expr_set> Container; Container vars; unsigned size; public: ArrayVars(); void insert(z3::expr const &); bool isEmpty() const; unsigned getSize() const; bool areCommonPairsAvaible() const; Container::const_iterator begin() const; Container::const_iterator end() const; }; private: // normalizeInput accomplishes the following: // 1. Removes applications of length(x) // replacing them with diff(x, empty_array) // of the appropriate type // 2. Remove applications of not // 3. Replace select by rd of the appropriate // type // 4. Replace store by wr of the appropriate // type z3::expr normalizeInputDefault(z3::expr const &); z3::expr normalizeInput(z3::expr const &); void flattenPredicate( z3::expr const &, SideInterpolant, unsigned &); void flattenPredicateAux( z3::expr const &, SideInterpolant, unsigned &); void flattenTerm( z3::expr const &, SideInterpolant, unsigned &); void cojoin(z3::expr const &, z3::expr const &, SideInterpolant, unsigned &); void updateArrayVars( z3::expr const &, SideInterpolant); void updateIndexVars( z3::expr const &, SideInterpolant); void updateVarsDB( z3::expr const &, SideInterpolant); z3::expr fresh_index_constant(); z3::expr fresh_array_constant(z3::sort const &); z3::expr fresh_constant(z3::sort const &); AXDSignature & sig; unsigned fresh_num; z3::expr_vector input_part_a, input_part_b; AXDSignature::z3_expr_vector_unique part_a_index_vars, part_b_index_vars; ArrayVars part_a_array_vars, part_b_array_vars, common_array_vars; //AXDSignature::z3_expr_set //part_a_array_vars, //part_b_array_vars, //common_array_vars; public: Preprocessor(AXDSignature &, z3::expr const &, z3::expr const &); friend std::ostream & operator << ( std::ostream &, Preprocessor::ArrayVars const &); }; #endif
typesAreSpaces/AXDInterpolator
include/AXDSignature.h
<gh_stars>0 #ifndef _AXD_SIG_ #define _AXD_SIG_ #include <ios> #define FRESH_ARRAY_PREFIX "fresh_array_" #define FRESH_ELEMENT_PREFIX "fresh_element_" #define FRESH_INDEX_PREFIX "fresh_index_" #define FRESH_COMMON_PREFIX "fresh_" #define DETECT_THEORY 1 //#define m_out std::cerr #define m_out std::cout #define inSet(element, set) (set.find(element) != set.end()) #define lhs(x) x.arg(0) #define rhs(x) x.arg(1) #define func_name(x) x.decl().name().str() #define _get_sort(x) x.decl().range() #define sort_name(x) x.decl().range().name().str() #define func_kind(x) x.decl().decl_kind() #include "z3++.h" #include <set> #include <cstring> #include <utility> #include <regex> #include <map> #include <algorithm> // Notes: // The implementation considers // elements of any index theory // to have int sort. struct AXDSignature { enum TheoryName { QF_TO, QF_IDL, QF_UTVPI, QF_LIA }; struct Z3ExprComparator { bool operator() ( z3::expr const & a, z3::expr const & b) const; }; typedef std::set<z3::expr, Z3ExprComparator> z3_expr_set; class z3_expr_vector_unique : public z3::expr_vector { std::set<unsigned> expr_ids; public: z3_expr_vector_unique(z3::context &); void push(z3::expr const &); }; class z3_sort_vector_unique : public z3::sort_vector { std::set<unsigned> sort_ids; public: z3_sort_vector_unique(z3::context &); void push(z3::sort const &); }; static bool isSpaceOrParen(char); void extractNameFromSort(std::string &) const; void processArrayDecls(std::string &); void indexElementSorts(); bool is_QF_TO() const; bool is_QF_IDL() const; bool isArraySort(z3::sort const &) const; void setTheory(TheoryName); TheoryName const & getTheoryName() const; z3::sort getArraySortBySort(z3::sort const &) const; z3::sort getArraySortBySort(unsigned) const; z3::expr getUndefinedBySort(z3::sort const &) const; z3::expr getUndefinedBySort(unsigned) const; z3::expr getEmptyArrayBySort(z3::sort const &) const; z3::expr getEmptyArrayBySort(unsigned) const; z3::func_decl getDiffBySort(z3::sort const &) const; z3::func_decl getDiffBySort(unsigned) const; z3::func_decl getDiff_BySort(z3::sort const &) const; z3::func_decl getDiff_BySort(unsigned) const; z3::func_decl getWrBySort(z3::sort const &) const; z3::func_decl getWrBySort(unsigned) const; z3::func_decl getRdBySort(z3::sort const &) const; z3::func_decl getRdBySort(unsigned) const; friend std::ostream & operator << ( std::ostream &, z3_expr_set const &); friend std::ostream & operator << ( std::ostream &, TheoryName const &); z3::context & ctx; TheoryName theory_name; z3::sort const bool_sort, int_sort; // "es" stands for elements sorts z3_sort_vector_unique element_sorts; z3::sort_vector array_sorts; z3::expr_vector undefined_es; z3::expr_vector empty_array_es; z3::func_decl_vector diff_es, diff_k_es, wr_es, rd_es, length_es; // 1. Given the id() of a type A // returns the indexing-position of the abstract type ArraySortA // 2. Given the id() of an abstract type ArraySortA // returns the indexing-position of the abstract type ArraySortA std::map<unsigned, unsigned> array_sort_map; AXDSignature(z3::context &, char const *, std::string &); }; #endif
typesAreSpaces/AXDInterpolator
tests/benchmark/include/UAutomizerFileReader.h
#include <iostream> #include <cassert> #include <regex> #include <fstream> #include <string> #include <type_traits> #include <vector> #include <cstring> #include <stdio.h> #include <string> #include <cstdlib> #include <regex> #include "z3++.h" #define SINGLE_FORMULA 0 #define REPORT_BAD_CASES 0 #define TEMP_FILE_SETUP\ std::string temp_file =\ "temp_" + name_solver + "_" + current_file;\ std::ofstream smt_file (temp_file.c_str());\ \ for(auto const & x : stack_of_frames)\ smt_file << x << std::endl;\ smt_file << current_frame << std::endl;\ smt_file.close();\ #define BENCHMARK_COMMAND(WRITER, EXEC_COMMAND, LOG_COMMAND)\ z3::context ctx;\ z3::solver input_parser(ctx, "QF_AUFLIA");\ input_parser.from_file(temp_file.c_str());\ \ for(auto const & x : input_parser.assertions()){\ if(hasNonSupportedSymbols(x)){\ system(("rm -rf " + temp_file).c_str());\ return;\ }\ }\ \ if(input_parser.check() == z3::unsat){\ std::string file_for_implementation =\ "axdinterpolator_" + name_solver + "_" + current_file;\ std::ofstream axdinterpolator_file(file_for_implementation.c_str());\ \ z3::expr_vector curr_assertions = input_parser.assertions();\ z3::expr_vector part_a(ctx), part_b(ctx);\ \ auto const & to_cnf_tactic = \ z3::tactic(ctx, "tseitin-cnf");\ \ z3::goal goal_assertions(ctx);\ goal_assertions.add(z3::mk_and(curr_assertions));\ auto const & cnf_assertions = to_cnf_tactic(goal_assertions);\ \ assert(cnf_assertions.size() == 1);\ z3::expr const & curr_conjunction = cnf_assertions[0].as_expr();\ \ unsigned total_size_cnf = curr_conjunction.num_args();\ unsigned half_size_cnf = total_size_cnf/2;\ if(curr_conjunction.decl().decl_kind() != Z3_OP_AND\ || half_size_cnf == 0\ || (total_size_cnf - half_size_cnf) == 0 \ ){\ axdinterpolator_file.close();\ system(("rm -rf " + file_for_implementation).c_str());\ system(("rm -rf " + temp_file).c_str());\ return;\ }\ \ part_a.push_back(ctx.bool_val(true));\ part_b.push_back(ctx.bool_val(true));\ for(unsigned i = 0; i < half_size_cnf; i++)\ part_a.push_back(curr_conjunction.arg(i));\ for(unsigned i = half_size_cnf; i < total_size_cnf; i++)\ part_b.push_back(curr_conjunction.arg(i));\ \ WRITER;\ \ char exec_command[1000];\ EXEC_COMMAND;\ int ret = system(exec_command);\ char log_command[1000];\ LOG_COMMAND;\ system(log_command);\ \ system(("rm -rf " + file_for_implementation).c_str());\ } enum BENCHMARK_EXIT_CODE { SUCCESS, FAILED, TIMEOUT }; enum SMT_SOLVER { Z3, MATHSAT, SMTINTERPOL }; class UAutomizerFileReader { std::string line, current_frame, current_file; int nesting_level, max_nesting_level; unsigned num; bool is_mem_safety_track; std::vector<std::string> stack_of_frames; SMT_SOLVER curr_solver; std::string const name_solver; unsigned num_samples; char * const file_statistics; bool test_our_implementation; bool hasNonSupportedSymbols(z3::expr const &) const; std::string nameAssertionsZ3(std::string const &) const; std::string nameAssertionsMathsat(std::string const &) const; bool isPushCmd() const; bool isPopCmd() const; bool isEchoCmd() const; void testAXDInterpolator() const; void testOtherSolvers(); void reset(); public: UAutomizerFileReader(SMT_SOLVER, unsigned, char * const, bool, bool); void process(char const *); void processSingleFile(char const *); };
viktyz/ANSPicker
ANSPicker/ANSPickerUI.h
<reponame>viktyz/ANSPicker // // ANSPickerUI.h // ANSPicker // // Created by viktyz on 17/5/18. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface ANSPickerUI : NSObject - (void)pickerEnter:(BOOL)open; - (void)updateTitle:(NSString *)title; @end
viktyz/ANSPicker
ANSPicker/NSURLRequest+Picker.h
// // NSURLRequest+Picker.h // ANSPicker // // Created by viktyz on 17/5/18. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface NSURLRequest (Picker) @end
viktyz/ANSPicker
ANSPickerDemo/ViewController.h
// // ViewController.h // ANSPickerDemo // // Created by viktyz on 2017/5/19. // Copyright © 2017年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
viktyz/ANSPicker
ANSPicker/ANSPicker.h
<reponame>viktyz/ANSPicker // // ANSPicker.h // ANSPicker // // Created by viktyz on 17/5/18. // Copyright © 2017 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface ANSPickerModel : NSObject @property (nonatomic, strong) NSURL *source; @property (nonatomic, strong) NSURL *dest; @property (nonatomic, assign) NSInteger count; @property (nonatomic, assign) NSTimeInterval lastRequestTime; - (instancetype)initWithSource:(NSURL *)source; @end @interface ANSPicker : NSObject @property (nonatomic, assign, readonly) BOOL active; + (instancetype)sharedPicker; - (void)pickerEnter:(BOOL)open; - (NSURL *)exchange:(NSURL *)url; - (NSArray *)recordList; - (void)clear; - (void)changeSource:(NSURL *)source dest:(NSURL *)dest; @end
PocketSwift/PocketNet
PocketNet/PocketNet.h
<filename>PocketNet/PocketNet.h<gh_stars>10-100 #import <UIKit/UIKit.h> //! Project version number for PocketNet. FOUNDATION_EXPORT double PocketNetVersionNumber; //! Project version string for PocketNet. FOUNDATION_EXPORT const unsigned char PocketNetVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <PocketNet/PublicHeader.h>
falsandtru/foundationdb-haskell
include/fdbc_wrapper.h
<gh_stars>1-10 #ifndef FDBC_WRAPPER #define FDBC_WRAPPER #define FDB_API_VERSION 600 #include "foundationdb/fdb_c.h" #include "foundationdb/fdb_c_options.g.h" // wasn't sure how to call a function-like macro in c2hs, so wrapped it here. fdb_error_t select_api_version(int runtime_version); #endif //FDBC_WRAPPER
Tejaswini-TR/swap-numbers
swap numbers.c
<reponame>Tejaswini-TR/swap-numbers<filename>swap numbers.c #include<stdio.h> int main() { int a,b; a=5; b=7; printf("before swap a= %d b=%d \n",a,b); a=a+b; b=a-b; a=a-b; printf("after swap a=%d and b=%d",a,b); return 0; }
grizzlygarillaz/vkService
nodejs/include/node/cppgc/heap.h
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef INCLUDE_CPPGC_HEAP_H_ #define INCLUDE_CPPGC_HEAP_H_ #include <memory> #include <vector> #include "cppgc/common.h" #include "cppgc/custom-space.h" #include "v8config.h" // NOLINT(build/include_directory) namespace cppgc { namespace internal { class Heap; } // namespace internal class V8_EXPORT Heap { public: /** * Specifies the stack state the embedder is in. */ using StackState = EmbedderStackState; struct HeapOptions { static HeapOptions Default() { return {}; } /** * Custom spaces added to heap are required to have indices forming a * numbered sequence starting at 0, i.e., their kSpaceIndex must correspond * to the index they reside in the vector. */ std::vector<std::unique_ptr<CustomSpaceBase>> custom_spaces; }; static std::unique_ptr<Heap> Create(HeapOptions = HeapOptions::Default()); virtual ~Heap() = default; /** * Forces garbage collection. * * \param source String specifying the source (or caller) triggering a * forced garbage collection. * \param reason String specifying the reason for the forced garbage * collection. * \param stack_state The embedder stack state, see StackState. */ void ForceGarbageCollectionSlow( const char* source, const char* reason, StackState stack_state = StackState::kMayContainHeapPointers); private: Heap() = default; friend class internal::Heap; }; } // namespace cppgc #endif // INCLUDE_CPPGC_HEAP_H_
grizzlygarillaz/vkService
nodejs/include/node/v8-wasm-trap-handler-posix.h
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_WASM_TRAP_HANDLER_POSIX_H_ #define V8_WASM_TRAP_HANDLER_POSIX_H_ #include <signal.h> #include "v8config.h" // NOLINT(build/include_directory) namespace v8 { /** * This function determines whether a memory access violation has been an * out-of-bounds memory access in WebAssembly. If so, it will modify the context * parameter and add a return address where the execution can continue after the * signal handling, and return true. Otherwise, false will be returned. * * The parameters to this function correspond to those passed to a Posix signal * handler. Use this function only on Linux and Mac. * * \param sig_code The signal code, e.g. SIGSEGV. * \param info A pointer to the siginfo_t struct provided to the signal handler. * \param context A pointer to a ucontext_t struct provided to the signal * handler. */ V8_EXPORT bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t* info, void* context); } // namespace v8 #endif // V8_WASM_TRAP_HANDLER_POSIX_H_
grizzlygarillaz/vkService
nodejs/include/node/cppgc/internal/accessors.h
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef INCLUDE_CPPGC_INTERNAL_ACCESSORS_H_ #define INCLUDE_CPPGC_INTERNAL_ACCESSORS_H_ #include "cppgc/internal/api-constants.h" namespace cppgc { class Heap; namespace internal { inline cppgc::Heap* GetHeapFromPayload(const void* payload) { return *reinterpret_cast<cppgc::Heap**>( ((reinterpret_cast<uintptr_t>(payload) & api_constants::kPageBaseMask) + api_constants::kGuardPageSize) + api_constants::kHeapOffset); } } // namespace internal } // namespace cppgc #endif // INCLUDE_CPPGC_INTERNAL_ACCESSORS_H_
grizzlygarillaz/vkService
nodejs/include/node/v8-util.h
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_UTIL_H_ #define V8_UTIL_H_ #include "v8.h" // NOLINT(build/include_directory) #include <assert.h> #include <map> #include <vector> /** * Support for Persistent containers. * * C++11 embedders can use STL containers with Global values, * but pre-C++11 does not support the required move semantic and hence * may want these container classes. */ namespace v8 { typedef uintptr_t PersistentContainerValue; static const uintptr_t kPersistentContainerNotFound = 0; enum PersistentContainerCallbackType { kNotWeak, // These correspond to v8::WeakCallbackType kWeakWithParameter, kWeakWithInternalFields }; /** * A default trait implementation for PersistentValueMap which uses std::map * as a backing map. * * Users will have to implement their own weak callbacks & dispose traits. */ template<typename K, typename V> class StdMapTraits { public: // STL map & related: typedef std::map<K, PersistentContainerValue> Impl; typedef typename Impl::iterator Iterator; static bool Empty(Impl* impl) { return impl->empty(); } static size_t Size(Impl* impl) { return impl->size(); } static void Swap(Impl& a, Impl& b) { std::swap(a, b); } // NOLINT static Iterator Begin(Impl* impl) { return impl->begin(); } static Iterator End(Impl* impl) { return impl->end(); } static K Key(Iterator it) { return it->first; } static PersistentContainerValue Value(Iterator it) { return it->second; } static PersistentContainerValue Set(Impl* impl, K key, PersistentContainerValue value) { std::pair<Iterator, bool> res = impl->insert(std::make_pair(key, value)); PersistentContainerValue old_value = kPersistentContainerNotFound; if (!res.second) { old_value = res.first->second; res.first->second = value; } return old_value; } static PersistentContainerValue Get(Impl* impl, K key) { Iterator it = impl->find(key); if (it == impl->end()) return kPersistentContainerNotFound; return it->second; } static PersistentContainerValue Remove(Impl* impl, K key) { Iterator it = impl->find(key); if (it == impl->end()) return kPersistentContainerNotFound; PersistentContainerValue value = it->second; impl->erase(it); return value; } }; /** * A default trait implementation for PersistentValueMap, which inherits * a std:map backing map from StdMapTraits and holds non-weak persistent * objects and has no special Dispose handling. * * You should not derive from this class, since MapType depends on the * surrounding class, and hence a subclass cannot simply inherit the methods. */ template<typename K, typename V> class DefaultPersistentValueMapTraits : public StdMapTraits<K, V> { public: // Weak callback & friends: static const PersistentContainerCallbackType kCallbackType = kNotWeak; typedef PersistentValueMap<K, V, DefaultPersistentValueMapTraits<K, V> > MapType; typedef void WeakCallbackDataType; static WeakCallbackDataType* WeakCallbackParameter( MapType* map, const K& key, Local<V> value) { return nullptr; } static MapType* MapFromWeakCallbackInfo( const WeakCallbackInfo<WeakCallbackDataType>& data) { return nullptr; } static K KeyFromWeakCallbackInfo( const WeakCallbackInfo<WeakCallbackDataType>& data) { return K(); } static void DisposeCallbackData(WeakCallbackDataType* data) { } static void Dispose(Isolate* isolate, Global<V> value, K key) {} }; template <typename K, typename V> class DefaultGlobalMapTraits : public StdMapTraits<K, V> { private: template <typename T> struct RemovePointer; public: // Weak callback & friends: static const PersistentContainerCallbackType kCallbackType = kNotWeak; typedef GlobalValueMap<K, V, DefaultGlobalMapTraits<K, V> > MapType; typedef void WeakCallbackDataType; static WeakCallbackDataType* WeakCallbackParameter(MapType* map, const K& key, Local<V> value) { return nullptr; } static MapType* MapFromWeakCallbackInfo( const WeakCallbackInfo<WeakCallbackDataType>& data) { return nullptr; } static K KeyFromWeakCallbackInfo( const WeakCallbackInfo<WeakCallbackDataType>& data) { return K(); } static void DisposeCallbackData(WeakCallbackDataType* data) {} static void OnWeakCallback( const WeakCallbackInfo<WeakCallbackDataType>& data) {} static void Dispose(Isolate* isolate, Global<V> value, K key) {} // This is a second pass callback, so SetSecondPassCallback cannot be called. static void DisposeWeak(const WeakCallbackInfo<WeakCallbackDataType>& data) {} private: template <typename T> struct RemovePointer<T*> { typedef T Type; }; }; /** * A map wrapper that allows using Global as a mapped value. * C++11 embedders don't need this class, as they can use Global * directly in std containers. * * The map relies on a backing map, whose type and accessors are described * by the Traits class. The backing map will handle values of type * PersistentContainerValue, with all conversion into and out of V8 * handles being transparently handled by this class. */ template <typename K, typename V, typename Traits> class PersistentValueMapBase { public: Isolate* GetIsolate() { return isolate_; } /** * Return size of the map. */ size_t Size() { return Traits::Size(&impl_); } /** * Return whether the map holds weak persistents. */ bool IsWeak() { return Traits::kCallbackType != kNotWeak; } /** * Get value stored in map. */ Local<V> Get(const K& key) { return Local<V>::New(isolate_, FromVal(Traits::Get(&impl_, key))); } /** * Check whether a value is contained in the map. */ bool Contains(const K& key) { return Traits::Get(&impl_, key) != kPersistentContainerNotFound; } /** * Get value stored in map and set it in returnValue. * Return true if a value was found. */ bool SetReturnValue(const K& key, ReturnValue<Value> returnValue) { return SetReturnValueFromVal(&returnValue, Traits::Get(&impl_, key)); } /** * Return value for key and remove it from the map. */ Global<V> Remove(const K& key) { return Release(Traits::Remove(&impl_, key)).Pass(); } /** * Traverses the map repeatedly, * in case side effects of disposal cause insertions. **/ void Clear() { typedef typename Traits::Iterator It; HandleScope handle_scope(isolate_); // TODO(dcarney): figure out if this swap and loop is necessary. while (!Traits::Empty(&impl_)) { typename Traits::Impl impl; Traits::Swap(impl_, impl); for (It i = Traits::Begin(&impl); i != Traits::End(&impl); ++i) { Traits::Dispose(isolate_, Release(Traits::Value(i)).Pass(), Traits::Key(i)); } } } /** * Helper class for GetReference/SetWithReference. Do not use outside * that context. */ class PersistentValueReference { public: PersistentValueReference() : value_(kPersistentContainerNotFound) { } PersistentValueReference(const PersistentValueReference& other) : value_(other.value_) { } Local<V> NewLocal(Isolate* isolate) const { return Local<V>::New(isolate, FromVal(value_)); } bool IsEmpty() const { return value_ == kPersistentContainerNotFound; } template<typename T> bool SetReturnValue(ReturnValue<T> returnValue) { return SetReturnValueFromVal(&returnValue, value_); } void Reset() { value_ = kPersistentContainerNotFound; } void operator=(const PersistentValueReference& other) { value_ = other.value_; } private: friend class PersistentValueMapBase; friend class PersistentValueMap<K, V, Traits>; friend class GlobalValueMap<K, V, Traits>; explicit PersistentValueReference(PersistentContainerValue value) : value_(value) { } void operator=(PersistentContainerValue value) { value_ = value; } PersistentContainerValue value_; }; /** * Get a reference to a map value. This enables fast, repeated access * to a value stored in the map while the map remains unchanged. * * Careful: This is potentially unsafe, so please use with care. * The value will become invalid if the value for this key changes * in the underlying map, as a result of Set or Remove for the same * key; as a result of the weak callback for the same key; or as a * result of calling Clear() or destruction of the map. */ PersistentValueReference GetReference(const K& key) { return PersistentValueReference(Traits::Get(&impl_, key)); } protected: explicit PersistentValueMapBase(Isolate* isolate) : isolate_(isolate), label_(nullptr) {} PersistentValueMapBase(Isolate* isolate, const char* label) : isolate_(isolate), label_(label) {} ~PersistentValueMapBase() { Clear(); } Isolate* isolate() { return isolate_; } typename Traits::Impl* impl() { return &impl_; } static V* FromVal(PersistentContainerValue v) { return reinterpret_cast<V*>(v); } static PersistentContainerValue ClearAndLeak(Global<V>* persistent) { V* v = persistent->val_; persistent->val_ = nullptr; return reinterpret_cast<PersistentContainerValue>(v); } static PersistentContainerValue Leak(Global<V>* persistent) { return reinterpret_cast<PersistentContainerValue>(persistent->val_); } /** * Return a container value as Global and make sure the weak * callback is properly disposed of. All remove functionality should go * through this. */ static Global<V> Release(PersistentContainerValue v) { Global<V> p; p.val_ = FromVal(v); if (Traits::kCallbackType != kNotWeak && p.IsWeak()) { Traits::DisposeCallbackData( p.template ClearWeak<typename Traits::WeakCallbackDataType>()); } return p.Pass(); } void RemoveWeak(const K& key) { Global<V> p; p.val_ = FromVal(Traits::Remove(&impl_, key)); p.Reset(); } void AnnotateStrongRetainer(Global<V>* persistent) { persistent->AnnotateStrongRetainer(label_); } private: PersistentValueMapBase(PersistentValueMapBase&); void operator=(PersistentValueMapBase&); static bool SetReturnValueFromVal(ReturnValue<Value>* returnValue, PersistentContainerValue value) { bool hasValue = value != kPersistentContainerNotFound; if (hasValue) { returnValue->SetInternal( *reinterpret_cast<internal::Address*>(FromVal(value))); } return hasValue; } Isolate* isolate_; typename Traits::Impl impl_; const char* label_; }; template <typename K, typename V, typename Traits> class PersistentValueMap : public PersistentValueMapBase<K, V, Traits> { public: explicit PersistentValueMap(Isolate* isolate) : PersistentValueMapBase<K, V, Traits>(isolate) {} PersistentValueMap(Isolate* isolate, const char* label) : PersistentValueMapBase<K, V, Traits>(isolate, label) {} typedef typename PersistentValueMapBase<K, V, Traits>::PersistentValueReference PersistentValueReference; /** * Put value into map. Depending on Traits::kIsWeak, the value will be held * by the map strongly or weakly. * Returns old value as Global. */ Global<V> Set(const K& key, Local<V> value) { Global<V> persistent(this->isolate(), value); return SetUnique(key, &persistent); } /** * Put value into map, like Set(const K&, Local<V>). */ Global<V> Set(const K& key, Global<V> value) { return SetUnique(key, &value); } /** * Put the value into the map, and set the 'weak' callback when demanded * by the Traits class. */ Global<V> SetUnique(const K& key, Global<V>* persistent) { if (Traits::kCallbackType == kNotWeak) { this->AnnotateStrongRetainer(persistent); } else { WeakCallbackType callback_type = Traits::kCallbackType == kWeakWithInternalFields ? WeakCallbackType::kInternalFields : WeakCallbackType::kParameter; Local<V> value(Local<V>::New(this->isolate(), *persistent)); persistent->template SetWeak<typename Traits::WeakCallbackDataType>( Traits::WeakCallbackParameter(this, key, value), WeakCallback, callback_type); } PersistentContainerValue old_value = Traits::Set(this->impl(), key, this->ClearAndLeak(persistent)); return this->Release(old_value).Pass(); } /** * Put a value into the map and update the reference. * Restrictions of GetReference apply here as well. */ Global<V> Set(const K& key, Global<V> value, PersistentValueReference* reference) { *reference = this->Leak(&value); return SetUnique(key, &value); } private: static void WeakCallback( const WeakCallbackInfo<typename Traits::WeakCallbackDataType>& data) { if (Traits::kCallbackType != kNotWeak) { PersistentValueMap<K, V, Traits>* persistentValueMap = Traits::MapFromWeakCallbackInfo(data); K key = Traits::KeyFromWeakCallbackInfo(data); Traits::Dispose(data.GetIsolate(), persistentValueMap->Remove(key).Pass(), key); Traits::DisposeCallbackData(data.GetParameter()); } } }; template <typename K, typename V, typename Traits> class GlobalValueMap : public PersistentValueMapBase<K, V, Traits> { public: explicit GlobalValueMap(Isolate* isolate) : PersistentValueMapBase<K, V, Traits>(isolate) {} GlobalValueMap(Isolate* isolate, const char* label) : PersistentValueMapBase<K, V, Traits>(isolate, label) {} typedef typename PersistentValueMapBase<K, V, Traits>::PersistentValueReference PersistentValueReference; /** * Put value into map. Depending on Traits::kIsWeak, the value will be held * by the map strongly or weakly. * Returns old value as Global. */ Global<V> Set(const K& key, Local<V> value) { Global<V> persistent(this->isolate(), value); return SetUnique(key, &persistent); } /** * Put value into map, like Set(const K&, Local<V>). */ Global<V> Set(const K& key, Global<V> value) { return SetUnique(key, &value); } /** * Put the value into the map, and set the 'weak' callback when demanded * by the Traits class. */ Global<V> SetUnique(const K& key, Global<V>* persistent) { if (Traits::kCallbackType == kNotWeak) { this->AnnotateStrongRetainer(persistent); } else { WeakCallbackType callback_type = Traits::kCallbackType == kWeakWithInternalFields ? WeakCallbackType::kInternalFields : WeakCallbackType::kParameter; Local<V> value(Local<V>::New(this->isolate(), *persistent)); persistent->template SetWeak<typename Traits::WeakCallbackDataType>( Traits::WeakCallbackParameter(this, key, value), OnWeakCallback, callback_type); } PersistentContainerValue old_value = Traits::Set(this->impl(), key, this->ClearAndLeak(persistent)); return this->Release(old_value).Pass(); } /** * Put a value into the map and update the reference. * Restrictions of GetReference apply here as well. */ Global<V> Set(const K& key, Global<V> value, PersistentValueReference* reference) { *reference = this->Leak(&value); return SetUnique(key, &value); } private: static void OnWeakCallback( const WeakCallbackInfo<typename Traits::WeakCallbackDataType>& data) { if (Traits::kCallbackType != kNotWeak) { auto map = Traits::MapFromWeakCallbackInfo(data); K key = Traits::KeyFromWeakCallbackInfo(data); map->RemoveWeak(key); Traits::OnWeakCallback(data); data.SetSecondPassCallback(SecondWeakCallback); } } static void SecondWeakCallback( const WeakCallbackInfo<typename Traits::WeakCallbackDataType>& data) { Traits::DisposeWeak(data); } }; /** * A map that uses Global as value and std::map as the backing * implementation. Persistents are held non-weak. * * C++11 embedders don't need this class, as they can use * Global directly in std containers. */ template<typename K, typename V, typename Traits = DefaultPersistentValueMapTraits<K, V> > class StdPersistentValueMap : public PersistentValueMap<K, V, Traits> { public: explicit StdPersistentValueMap(Isolate* isolate) : PersistentValueMap<K, V, Traits>(isolate) {} }; /** * A map that uses Global as value and std::map as the backing * implementation. Globals are held non-weak. * * C++11 embedders don't need this class, as they can use * Global directly in std containers. */ template <typename K, typename V, typename Traits = DefaultGlobalMapTraits<K, V> > class StdGlobalValueMap : public GlobalValueMap<K, V, Traits> { public: explicit StdGlobalValueMap(Isolate* isolate) : GlobalValueMap<K, V, Traits>(isolate) {} }; class DefaultPersistentValueVectorTraits { public: typedef std::vector<PersistentContainerValue> Impl; static void Append(Impl* impl, PersistentContainerValue value) { impl->push_back(value); } static bool IsEmpty(const Impl* impl) { return impl->empty(); } static size_t Size(const Impl* impl) { return impl->size(); } static PersistentContainerValue Get(const Impl* impl, size_t i) { return (i < impl->size()) ? impl->at(i) : kPersistentContainerNotFound; } static void ReserveCapacity(Impl* impl, size_t capacity) { impl->reserve(capacity); } static void Clear(Impl* impl) { impl->clear(); } }; /** * A vector wrapper that safely stores Global values. * C++11 embedders don't need this class, as they can use Global * directly in std containers. * * This class relies on a backing vector implementation, whose type and methods * are described by the Traits class. The backing map will handle values of type * PersistentContainerValue, with all conversion into and out of V8 * handles being transparently handled by this class. */ template<typename V, typename Traits = DefaultPersistentValueVectorTraits> class PersistentValueVector { public: explicit PersistentValueVector(Isolate* isolate) : isolate_(isolate) { } ~PersistentValueVector() { Clear(); } /** * Append a value to the vector. */ void Append(Local<V> value) { Global<V> persistent(isolate_, value); Traits::Append(&impl_, ClearAndLeak(&persistent)); } /** * Append a persistent's value to the vector. */ void Append(Global<V> persistent) { Traits::Append(&impl_, ClearAndLeak(&persistent)); } /** * Are there any values in the vector? */ bool IsEmpty() const { return Traits::IsEmpty(&impl_); } /** * How many elements are in the vector? */ size_t Size() const { return Traits::Size(&impl_); } /** * Retrieve the i-th value in the vector. */ Local<V> Get(size_t index) const { return Local<V>::New(isolate_, FromVal(Traits::Get(&impl_, index))); } /** * Remove all elements from the vector. */ void Clear() { size_t length = Traits::Size(&impl_); for (size_t i = 0; i < length; i++) { Global<V> p; p.val_ = FromVal(Traits::Get(&impl_, i)); } Traits::Clear(&impl_); } /** * Reserve capacity in the vector. * (Efficiency gains depend on the backing implementation.) */ void ReserveCapacity(size_t capacity) { Traits::ReserveCapacity(&impl_, capacity); } private: static PersistentContainerValue ClearAndLeak(Global<V>* persistent) { V* v = persistent->val_; persistent->val_ = nullptr; return reinterpret_cast<PersistentContainerValue>(v); } static V* FromVal(PersistentContainerValue v) { return reinterpret_cast<V*>(v); } Isolate* isolate_; typename Traits::Impl impl_; }; } // namespace v8 #endif // V8_UTIL_H
grizzlygarillaz/vkService
nodejs/include/node/cppgc/internal/gc-info.h
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef INCLUDE_CPPGC_INTERNAL_GC_INFO_H_ #define INCLUDE_CPPGC_INTERNAL_GC_INFO_H_ #include <stdint.h> #include "cppgc/internal/finalizer-trait.h" #include "v8config.h" // NOLINT(build/include_directory) namespace cppgc { namespace internal { using GCInfoIndex = uint16_t; class V8_EXPORT RegisteredGCInfoIndex final { public: RegisteredGCInfoIndex(FinalizationCallback finalization_callback, bool has_v_table); GCInfoIndex GetIndex() const { return index_; } private: const GCInfoIndex index_; }; // Trait determines how the garbage collector treats objects wrt. to traversing, // finalization, and naming. template <typename T> struct GCInfoTrait { static GCInfoIndex Index() { static_assert(sizeof(T), "T must be fully defined"); static const RegisteredGCInfoIndex registered_index( FinalizerTrait<T>::kCallback, std::is_polymorphic<T>::value); return registered_index.GetIndex(); } }; } // namespace internal } // namespace cppgc #endif // INCLUDE_CPPGC_INTERNAL_GC_INFO_H_
grizzlygarillaz/vkService
nodejs/include/node/cppgc/platform.h
<reponame>grizzlygarillaz/vkService // Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef INCLUDE_CPPGC_PLATFORM_H_ #define INCLUDE_CPPGC_PLATFORM_H_ #include "v8-platform.h" // NOLINT(build/include_directory) #include "v8config.h" // NOLINT(build/include_directory) namespace cppgc { // TODO(v8:10346): Put PageAllocator in a non-V8 include header to avoid // depending on namespace v8. using PageAllocator = v8::PageAllocator; // Initializes the garbage collector with the provided platform. Must be called // before creating a Heap. V8_EXPORT void InitializePlatform(PageAllocator* page_allocator); // Must be called after destroying the last used heap. V8_EXPORT void ShutdownPlatform(); namespace internal { V8_EXPORT void Abort(); } // namespace internal } // namespace cppgc #endif // INCLUDE_CPPGC_PLATFORM_H_
grizzlygarillaz/vkService
nodejs/include/node/cppgc/liveness-broker.h
<reponame>grizzlygarillaz/vkService // Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef INCLUDE_CPPGC_LIVENESS_BROKER_H_ #define INCLUDE_CPPGC_LIVENESS_BROKER_H_ #include "cppgc/heap.h" #include "cppgc/member.h" #include "cppgc/trace-trait.h" #include "v8config.h" // NOLINT(build/include_directory) namespace cppgc { namespace internal { class LivenessBrokerFactory; } // namespace internal class V8_EXPORT LivenessBroker final { public: template <typename T> bool IsHeapObjectAlive(const T* object) const { return object && IsHeapObjectAliveImpl( TraceTrait<T>::GetTraceDescriptor(object).base_object_payload); } template <typename T> bool IsHeapObjectAlive(const WeakMember<T>& weak_member) const { return (weak_member != kSentinelPointer) && IsHeapObjectAlive<T>(weak_member.Get()); } template <typename T> bool IsHeapObjectAlive(const UntracedMember<T>& untraced_member) const { return (untraced_member != kSentinelPointer) && IsHeapObjectAlive<T>(untraced_member.Get()); } private: LivenessBroker() = default; bool IsHeapObjectAliveImpl(const void*) const; friend class internal::LivenessBrokerFactory; }; } // namespace cppgc #endif // INCLUDE_CPPGC_LIVENESS_BROKER_H_
Nordstrom/xrpc-proto
gen-java-server/src/java_plugin/cpp/java_generator.h
<gh_stars>0 /* * Copyright 2018 Nordstrom, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * NOTICE: Modified from gRPC-java java_generator.h found at: * https://github.com/grpc/grpc-java/blob/dba2323585061f8634e37de7c757330826567a9d/compiler/src/java_plugin/cpp/java_generator.h */ #ifndef NET_GRPC_COMPILER_JAVA_GENERATOR_H_ #define NET_GRPC_COMPILER_JAVA_GENERATOR_H_ #include <stdlib.h> // for abort() #include <iostream> #include <string> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/descriptor.h> using namespace std; namespace java_xrpc_generator { // Returns the package name of the gRPC services defined in the given file. string ServiceJavaPackage(const google::protobuf::FileDescriptor *file); // Returns the name of the outer class that wraps in all the generated code for // the given service. string ServiceClassName(const google::protobuf::ServiceDescriptor *service); // Writes the generated service interface into the given ZeroCopyOutputStream void GenerateService(const google::protobuf::ServiceDescriptor *service, google::protobuf::io::ZeroCopyOutputStream *out); } // namespace java_grpc_generator #endif // NET_GRPC_COMPILER_JAVA_GENERATOR_H_
ahmetkcavusoglu/sio4
lines.h
#pragma once void drawLine(struct SSD1306& display, int8_t ax, int8_t ay, int8_t bx, int8_t by, bool jitter); void drawNum(struct SSD1306& display, int8_t digit, int8_t left, int8_t top, int8_t right, int8_t bottom, bool jitter); void drawLetter(struct SSD1306& display, char letter, int8_t left, int8_t top, int8_t right, int8_t bottom, bool jitter); void drawColon(struct SSD1306& display, int8_t radius, int8_t left, int8_t top, int8_t right, int8_t bottom, bool jitter); void drawPercent(struct SSD1306& display, int8_t left, int8_t top, int8_t right, int8_t bottom, bool jitter); template <typename T> T getMid(T a, T b) { return a + ((b - a) / 2); }
ahmetkcavusoglu/sio4
ssd1306.h
#pragma once #include <stdint.h> struct SSD1306 { void initialise(); void turnOff() const; void turnOn() const; void nonInvert() const; void invert() const; void setContrast(uint8_t level) const; void clear(int8_t val = 0); void flush() const; void setPixel(int8_t x, int8_t y); private: static uint8_t m_buffer[1024]; };
clearlove77/ZTQuickControl
ZTQuickControl/ZTQuickControl.h
// // ZTQuickControl.h // BlockUseDemo // // Created by quiet on 15/7/15. // Copyright (c) 2015年 quiet. All rights reserved. // #ifndef BlockUseDemo_ZTQuickControl_h #define BlockUseDemo_ZTQuickControl_h #import "UIView+ZTQuickControl.h" #import "UIView+ZTExtension.h" #endif
clearlove77/ZTQuickControl
ZTQuickControl/UIView+ZTQuickControl.h
<filename>ZTQuickControl/UIView+ZTQuickControl.h // // UIView+ZTQuickControl.h // BlockUseDemo // // Created by quiet on 15/7/15. // Copyright (c) 2015年 quiet. All rights reserved. // #import <UIKit/UIKit.h> #import "ZTButton.h" @interface UIView (ZTQuickControl) //创建系统按钮 -(UIButton *)addSystemButtonWithFrame:(CGRect)frame title:(NSString *)titile action:(void(^)(ZTButton *button))action; +(UIButton *)systemButtonWithFrame:(CGRect)frame title:(NSString *)titile action:(void(^)(ZTButton *button))action; //创建图片按钮 -(UIButton *)addImageButtonWithFrame:(CGRect)frame title:(NSString *)titile image:(NSString *)image action:(void(^)(ZTButton *button))action; //获取图片按钮(不直接添加到view) +(UIButton *)imageButtonWithFrame:(CGRect)frame title:(NSString *)titile image:(NSString *)image action:(void(^)(ZTButton *button))action; //创建label -(UILabel *)addLabelWithFrame:(CGRect)frame title:(NSString *)title; //创建imageView -(UIImageView *)addImageViewWithFrame:(CGRect)frame image:(NSString *)image; //创建textfiled -(UITextField *)addTextFieldWithFrame:(CGRect)frame style:(UITextBorderStyle)style delegate:(id)delegate; @end
clearlove77/ZTQuickControl
ZTQuickControl/ZTButton.h
<gh_stars>1-10 // // ZTButton.h // BlockUseDemo // // Created by quiet on 15/7/15. // Copyright (c) 2015年 quiet. All rights reserved. // #import <UIKit/UIKit.h> @interface ZTButton : UIButton //添加点击后执行的block // void action(ZTButton *button); @property (copy,nonatomic) void (^action)(ZTButton *button); @end
clearlove77/ZTQuickControl
ZTQuickControl/UIView+ZTExtension.h
// // UIView+ZTExtension.h // BlockUseDemo // // Created by quiet on 15/7/15. // Copyright (c) 2015年 quiet. All rights reserved. // #import <UIKit/UIKit.h> @interface UIView (ZTExtension) @property (nonatomic) CGFloat x; @property (nonatomic) CGFloat y; @property (nonatomic) CGFloat width; @property (nonatomic) CGFloat height; -(void)setCornerRadius:(CGFloat)radius; @end
samisaab/oopt-tai
inc/taihostif.h
<gh_stars>0 /** * @file taihostif.h * @brief This module defines the host interface for the Transponder * Abstraction Interface (TAI) * * @copyright Copyright (c) 2014 Microsoft Open Technologies, Inc. * @copyright Copyright (c) 2018 Nippon Telegraph and Telephone Corporation * @copyright Copyright (c) 2017 Cumulus Networks, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ #if !defined (__TAIHOSTIF_H_) #define __TAIHOSTIF_H_ #include <taitypes.h> /** * @defgroup TAIHOSTIF TAI - Host Interface specific API definitions * * @{ */ /** @brief A bitmap of lane faults */ typedef enum _tai_host_interface_lane_fault_t { TAI_HOST_INTERFACE_LANE_FAULT_LOSS_OF_LOCK, TAI_HOST_INTERFACE_LANE_FAULT_TX_FIFO_ERR } tai_host_interface_lane_fault_t; /** @brief The transmit alignment status */ typedef enum _tai_host_interface_tx_align_status_t { TAI_HOST_INTERFACE_TX_ALIGN_STATUS_CDR_LOCK_FAULT, TAI_HOST_INTERFACE_TX_ALIGN_STATUS_LOSS, TAI_HOST_INTERFACE_TX_ALIGN_STATUS_OUT, TAI_HOST_INTERFACE_TX_ALIGN_STATUS_DESKEW_LOCK } tai_host_interface_tx_align_status_t; /** @brief The host interface signal rate */ typedef enum _tai_host_interface_signal_rate_t { TAI_HOST_INTERFACE_SIGNAL_RATE_UNKNOWN, TAI_HOST_INTERFACE_SIGNAL_RATE_100_GBE, TAI_HOST_INTERFACE_SIGNAL_RATE_200_GBE, TAI_HOST_INTERFACE_SIGNAL_RATE_400_GBE, TAI_HOST_INTERFACE_SIGNAL_RATE_OTU4, TAI_HOST_INTERFACE_SIGNAL_RATE_MAX } tai_host_interface_signal_rate_t; /** @brief The host interface FEC type */ typedef enum _tai_host_interface_fec_type_t { TAI_HOST_INTERFACE_FEC_TYPE_NONE, /**< No FEC */ TAI_HOST_INTERFACE_FEC_TYPE_RS, /**< RS-FEC */ TAI_HOST_INTERFACE_FEC_TYPE_FC, /**< FC-FEC */ } tai_host_interface_fec_type_t; /** @brief The loopback types */ typedef enum _tai_host_interface_loopback_type_t { TAI_HOST_INTERFACE_LOOPBACK_TYPE_NONE, TAI_HOST_INTERFACE_LOOPBACK_TYPE_SHALLOW, TAI_HOST_INTERFACE_LOOPBACK_TYPE_DEEP, TAI_HOST_INTERFACE_LOOPBACK_TYPE_MAX } tai_host_interface_loopback_type_t; /** @brief The PCS alarm */ typedef enum _tai_host_interface_pcs_alarm_t { TAI_HOST_INTERFACE_PCS_ALARM_LOSS_OF_SIGNAL, TAI_HOST_INTERFACE_PCS_ALARM_LOSS_OF_FRAME, TAI_HOST_INTERFACE_PCS_ALARM_ILLEGAL_ALIGNMENT_MARKER, TAI_HOST_INTERFACE_PCS_ALARM_REMOTE_FAULT, TAI_HOST_INTERFACE_PCS_ALARM_LOCAL_FAULT, TAI_HOST_INTERFACE_PCS_ALARM_HI_BER, TAI_HOST_INTERFACE_PCS_ALARM_BIP_ERROR, TAI_HOST_INTERFACE_PCS_ALARM_DESKEW_ERROR, } tai_host_interface_pcs_alarm_t; /** * @brief Host interface Attribute Ids */ typedef enum _tai_host_interface_attr_t { /** * @brief Start of attributes */ TAI_HOST_INTERFACE_ATTR_START, /** * @brief The location of the host interface * * Used (and required) in the tai_create_host_interface_fn call. This allows * the adapter to uniquely identify the host interface on a module. * * @type #tai_uint32_t * @flags MANDATORY_ON_CREATE | CREATE_ONLY */ TAI_HOST_INTERFACE_ATTR_INDEX = TAI_HOST_INTERFACE_ATTR_START, /** * @brief Host lane fault status * * A list of lane fault status * * @type #tai_attr_value_list_t #tai_s32_list_t #tai_host_interface_lane_fault_t * @flags READ_ONLY */ TAI_HOST_INTERFACE_ATTR_LANE_FAULT, /** * @brief TX Alignment Status * * @type #tai_s32_list_t #tai_host_interface_tx_align_status_t * @flags READ_ONLY */ TAI_HOST_INTERFACE_ATTR_TX_ALIGN_STATUS, /** * @brief signal rate * * @type #tai_host_interface_signal_rate_t * @flags CREATE_AND_SET * @default vendor-specific */ TAI_HOST_INTERFACE_ATTR_SIGNAL_RATE, /** * @brief FEC type * * @type #tai_host_interface_fec_type_t * @flags CREATE_AND_SET * @default TAI_HOST_INTERFACE_FEC_TYPE_NONE */ TAI_HOST_INTERFACE_ATTR_FEC_TYPE, /** * @brief Loopback type * * @type #tai_host_interface_loopback_type_t * @flags CREATE_AND_SET * @default TAI_HOST_INTERFACE_LOOPBACK_TYPE_NONE */ TAI_HOST_INTERFACE_ATTR_LOOPBACK_TYPE, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_IN_OCTETS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_IN_PACKETS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_IN_FCS_ERRORS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_IN_MAC_ERRORS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_OUT_OCTETS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_OUT_PACKETS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_OUT_FCS_ERRORS, /** * @type #tai_uint32_t * @flags READ_ONLY | CLEARABLE */ TAI_HOST_INTERFACE_ATTR_ETHERNET_OUT_MAC_ERRORS, /** * @brief TX Ethernet PCS Alarm * * @type #tai_s32_list_t #tai_host_interface_pcs_alarm_t * @flags READ_ONLY */ TAI_HOST_INTERFACE_ATTR_TX_PCS_ALARM, /** * @brief RX Ethernet PCS Alarm * * @type #tai_s32_list_t #tai_host_interface_pcs_alarm_t * @flags READ_ONLY */ TAI_HOST_INTERFACE_ATTR_RX_PCS_ALARM, /** * @brief Host interface generic notification * * @type #tai_notification_handler_t * @flags CREATE_AND_SET * @default NULL */ TAI_HOST_INTERFACE_ATTR_NOTIFY, /** * @brief End of attributes */ TAI_HOST_INTERFACE_ATTR_END, /** Custom range base value */ TAI_HOST_INTERFACE_ATTR_CUSTOM_RANGE_START = 0x10000000, /** Custom range for the AC400 adapter */ TAI_HOST_INTERFACE_ATTR_CUSTOM_AC400_START = TAI_HOST_INTERFACE_ATTR_CUSTOM_RANGE_START, TAI_HOST_INTERFACE_ATTR_CUSTOM_AC400_END = TAI_HOST_INTERFACE_ATTR_CUSTOM_AC400_START + 0xFFFF, /** Custom range for the NLD0670APB/TRB100 adapter */ TAI_HOST_INTERFACE_ATTR_CUSTOM_NLD0670_TRB100_START, TAI_HOST_INTERFACE_ATTR_CUSTOM_NLD0670_TRB100_END = TAI_HOST_INTERFACE_ATTR_CUSTOM_NLD0670_TRB100_START + 0xFFFF, /** End of custom range base */ TAI_HOST_INTERFACE_ATTR_CUSTOM_RANGE_END } tai_host_interface_attr_t; /** * @brief Create host interface * * @param[out] host_interface_id Host interface id * @param[in] module_id Module ID containing the host interface * @param[in] attr_count Number of attributes * @param[in] attr_list Array of attributes * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_create_host_interface_fn)( _Out_ tai_object_id_t *host_interface_id, _In_ tai_object_id_t module_id, _In_ uint32_t attr_count, _In_ const tai_attribute_t *attr_list); /** * @brief Remove host interface * * @param[in] host_interface_id Host interface id * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_remove_host_interface_fn)( _In_ tai_object_id_t host_interface_id); /** * @brief Set host interface attribute value. * * @param[in] host_interface_id Host interface id * @param[in] attr Attribute * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_set_host_interface_attribute_fn)( _In_ tai_object_id_t host_interface_id, _In_ const tai_attribute_t *attr); /** * @brief Set multiple host interface attribute values * * @param[in] host_interface_id Host interface id * @param[in] attr_count Number of attributes * @param[in] attr_list Array of attributes * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_set_host_interface_attributes_fn)( _In_ tai_object_id_t host_interface_id, _In_ uint32_t attr_count, _In_ const tai_attribute_t *attr_list); /** * @brief Get host interface attribute * * @param[in] host_interface_id Host interface id * @param[inout] attr Attribute * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_get_host_interface_attribute_fn)( _In_ tai_object_id_t host_interface_id, _Inout_ tai_attribute_t *attr); /** * @brief Get multiple host interface attribute values * * @param[in] host_interface_id Host interface id * @param[in] attr_count Number of attributes * @param[inout] attr_list Array of attributes * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_get_host_interface_attributes_fn)( _In_ tai_object_id_t host_interface_id, _In_ uint32_t attr_count, _Inout_ tai_attribute_t *attr_list); /** * @brief Clear host interface attribute * * @param[in] host_interface_id Host interface id * @param[in] attr_id Attribute * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_clear_host_interface_attribute_fn)( _In_ tai_object_id_t host_interface_id, _In_ tai_attr_id_t attr_id); /** * @brief Clear multiple host interface attribute values * * @param[in] host_interface_id Host interface id * @param[in] attr_id_count Number of attribute ids * @param[in] attr_id_list Array of attribute ids * * @return #TAI_STATUS_SUCCESS on success, failure status code on error */ typedef tai_status_t (*tai_clear_host_interface_attributes_fn)( _In_ tai_object_id_t host_interface_id, _In_ uint32_t attr_id_count, _In_ tai_attr_id_t *attr_id); /** * @brief Host interface methods table retrieved with tai_api_query() */ typedef struct _tai_host_interface_api_t { tai_create_host_interface_fn create_host_interface; tai_remove_host_interface_fn remove_host_interface; tai_set_host_interface_attribute_fn set_host_interface_attribute; tai_set_host_interface_attributes_fn set_host_interface_attributes; tai_get_host_interface_attribute_fn get_host_interface_attribute; tai_get_host_interface_attributes_fn get_host_interface_attributes; tai_clear_host_interface_attribute_fn clear_host_interface_attribute; tai_clear_host_interface_attributes_fn clear_host_interface_attributes; } tai_host_interface_api_t; /** * @} */ #endif /** __TAIHOSTIF_H_ */
timgates42/x11fs
src/win_oper.c
<filename>src/win_oper.c #include "win_oper.h" #include "win_xcb.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "x11fs.h" //Specific read and write functions for each file void border_color_write(int wid, const char *buf) { set_border_color(wid, strtol(buf, NULL, 16)); } char *border_width_read(int wid) { int border_width=get_border_width(wid); if(border_width==-1){ errno = -EIO; return NULL; } //Work out the size needed to malloc by calling snprintf with a size of 0 char *border_width_string=malloc(snprintf(NULL, 0, "%d\n", border_width)+1); sprintf(border_width_string, "%d\n", border_width); return border_width_string; } void border_width_write(int wid, const char *buf) { set_border_width(wid, atoi(buf)); } char *root_width_read(int wid) { (void) wid; return geometry_width_read(-1); } char *root_height_read(int wid) { (void) wid; return geometry_height_read(-1); } char *geometry_width_read(int wid) { int width=get_width(wid); if(width==-1){ errno = -EIO; return NULL; } char *width_string=malloc(snprintf(NULL, 0, "%d\n", width)+1); sprintf(width_string, "%d\n", width); return width_string; } void geometry_width_write(int wid, const char *buf) { set_width(wid, atoi(buf)); } char *geometry_height_read(int wid) { int height=get_height(wid); if(height==-1){ errno = -EIO; return NULL; } char *height_string=malloc(snprintf(NULL, 0, "%d\n", height)+1); sprintf(height_string, "%d\n", height); return height_string; } void geometry_height_write(int wid, const char *buf) { set_height(wid, atoi(buf)); } char *geometry_x_read(int wid) { int x=get_x(wid); if(x==-1){ errno = -EIO; return NULL; } char *x_string=malloc(snprintf(NULL, 0, "%d\n", x)+1); sprintf(x_string, "%d\n", x); return x_string; } void geometry_x_write(int wid, const char *buf) { set_x(wid, atoi(buf)); } char *geometry_y_read(int wid) { int y=get_y(wid); if(y==-1){ errno = -EIO; return NULL; } char *y_string=malloc(snprintf(NULL, 0, "%d\n", y)+1); sprintf(y_string, "%d\n", y); return y_string; } void geometry_y_write(int wid, const char *buf) { set_y(wid, atoi(buf)); } char *mapped_read(int wid) { return strdup(get_mapped(wid) ? "true\n" : "false\n"); } void mapped_write(int wid, const char *buf) { if(!strcmp(buf, "true\n")) set_mapped(wid, true); if(!strcmp(buf, "false\n")) set_mapped(wid, false); } char *ignored_read(int wid) { return strdup(get_ignored(wid) ? "true\n" : "false\n"); } void ignored_write(int wid, const char *buf) { if(!strcmp(buf, "true\n")) set_ignored(wid, true); if(!strcmp(buf, "false\n")) set_ignored(wid, false); } void stack_write(int wid, const char *buf) { if(!strcmp(buf, "raise\n")) raise(wid); if(!strcmp(buf, "lower\n")) lower(wid); } char *title_read(int wid) { char *title=get_title(wid); size_t title_len = strlen(title); char *title_string=malloc(title_len+2); memset(title_string, 0, title_len+2); if ( title_len ) { sprintf(title_string, "%s\n", title); } free(title); return title_string; } char *class_read(int wid) { char **classes=get_class(wid); size_t class0_len = strlen(classes[0]), class1_len = strlen(classes[1]); char *class_string=malloc(class0_len + class1_len + 3); if ( class0_len ) { sprintf(class_string, "%s\n", classes[0]); } if ( class1_len ) { sprintf(class_string + class0_len + 1, "%s\n", classes[1]); } free(classes[0]); free(classes[1]); free(classes); return class_string; } char *event_read(int wid) { return get_events(); } char *focused_read(int wid) { (void) wid; char *focusedwin; int focusedid=focused(); if(focusedid){ focusedwin = malloc(WID_STRING_LENGTH+1); sprintf(focusedwin, "0x%08x\n", focusedid); }else{ focusedwin = malloc(6); sprintf(focusedwin, "root\n"); } return focusedwin; } void focused_write(int wid, const char *buf) { (void) wid; focus(strtol(buf, NULL, 16)); }
timgates42/x11fs
src/x11fs.c
#define FUSE_USE_VERSION 26 #include <stdio.h> #include <fuse.h> #include <stdlib.h> #include <stdbool.h> #include <errno.h> #include <string.h> #include <fnmatch.h> #include "x11fs.h" #include "win_xcb.h" #include "win_oper.h" //Represents a single file, contains pointers to the functions to call to read and write for that file struct x11fs_file{ const char *path; int mode; bool direct_io; bool dir; char *(*read)(int wid); void (*write)(int wid, const char *buf); }; //Our file layout static const struct x11fs_file x11fs_files[] = { {"/", S_IFDIR | 0700, false, true, NULL, NULL}, {"/root", S_IFDIR | 0700, false, true, NULL, NULL}, {"/root/geometry", S_IFDIR | 0700, false, true, NULL, NULL}, {"/root/geometry/width", S_IFREG | 0400, false, false, root_width_read, NULL}, {"/root/geometry/height", S_IFREG | 0400, false, false, root_height_read, NULL}, {"/0x*", S_IFDIR | 0700, false, true, NULL, NULL}, {"/0x*/border", S_IFDIR | 0700, false, true, NULL, NULL}, {"/0x*/border/color", S_IFREG | 0200, false, false, NULL, border_color_write}, {"/0x*/border/width", S_IFREG | 0600, false, false, border_width_read, border_width_write}, {"/0x*/geometry", S_IFDIR | 0700, false, true, NULL, NULL}, {"/0x*/geometry/width", S_IFREG | 0600, false, false, geometry_width_read, geometry_width_write}, {"/0x*/geometry/height", S_IFREG | 0600, false, false, geometry_height_read, geometry_height_write}, {"/0x*/geometry/x", S_IFREG | 0600, false, false, geometry_x_read, geometry_x_write}, {"/0x*/geometry/y", S_IFREG | 0600, false, false, geometry_y_read, geometry_y_write}, {"/0x*/mapped", S_IFREG | 0600, false, false, mapped_read, mapped_write}, {"/0x*/ignored", S_IFREG | 0600, false, false, ignored_read, ignored_write}, {"/0x*/stack", S_IFREG | 0200, false, false, NULL, stack_write}, {"/0x*/title", S_IFREG | 0400, false, false, title_read, NULL}, {"/0x*/class", S_IFREG | 0400, false, false, class_read, NULL}, {"/focused", S_IFREG | 0600, false, false, focused_read, focused_write}, {"/event", S_IFREG | 0400, true, false, event_read, NULL}, }; //Pull out the id of a window from a path static int get_winid(const char *path) { int wid = -1; //Check if the path is to a window directory or it's contents if(!strncmp(path, "/0x", 3) && sscanf(path, "/0x%08x", &wid) != 1){ wid = 0; } return wid; } //Runs when our filesystem is unmounted static void x11fs_destroy() { xcb_cleanup(); } //Doesn't actually do anything but it's required we implement this as it will get called when writing a value to a file that's shorter than the current contents static int x11fs_truncate(const char *path, off_t size) { return 0; } //Gives information about a file static int x11fs_getattr(const char *path, struct stat *stbuf) { //zero the information about the file memset(stbuf, 0, sizeof(struct stat)); //loop through our filesystem layout and check if the path matches one in our layout size_t files_length = sizeof(x11fs_files)/sizeof(struct x11fs_file); for(size_t i=0; i<files_length; i++){ if(!fnmatch(x11fs_files[i].path, path, FNM_PATHNAME)){ //if the path is to a window file, check that the window exists int wid; if((wid=get_winid(path)) != -1 && !exists(wid)){ return -ENOENT; } //if a path matches just use the information about the file from the layout stbuf->st_nlink = x11fs_files[i].dir ? 2 : 1; stbuf->st_mode = x11fs_files[i].mode; //Set the size of a file by getting its contents //If the file uses direct IO (it acts like a stream, just set size to 0) stbuf->st_size = 0; if((x11fs_files[i].read != NULL) && !(x11fs_files[i].direct_io)) { char *read_string=x11fs_files[i].read(wid); if(!read_string) return errno; stbuf->st_size=strlen(read_string); free(read_string); } return 0; } } //No such file or directory return -ENOENT; } //Gives the contents of a directory static int x11fs_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { (void) offset; (void) fi; //If the path is to a non existant window says so int wid; if((wid = get_winid(path)) != -1 && !exists(wid)){ return -ENOENT; } bool exists = false; bool dir = false; //Iterate through our filesystem layout size_t files_length = sizeof(x11fs_files)/sizeof(struct x11fs_file); for(size_t i=0; i<files_length; i++){ //If the path was to a window replace the wildcard in the layout with the actual window we're looking at char *matchpath; if((wid != -1) && (get_winid(x11fs_files[i].path) != -1)){ matchpath=malloc(strlen(x11fs_files[i].path)+8); sprintf(matchpath, "/0x%08x", wid); sprintf(matchpath+11, "%s", x11fs_files[i].path+4); } else matchpath=strdup(x11fs_files[i].path); //As the path for the root directory is just a / with no text we need to treat it as being 0 length //This is for when we check if something in our layout is in the folder we're looking at, but not in a subfolder int len = !strcmp(path, "/") ? 0 : strlen(path); //If the file exists in our layout if(!strncmp(path, matchpath, strlen(path))){ exists = true; //Check that to see if an element in our layout is directly below the folder we're looking at in the heirarchy //If so add it to the directory listing if((strlen(matchpath) > strlen(path)) && ((matchpath+len)[0] == '/') && !strchr(matchpath+len+1, '/')){ dir = true; //If it's a wildcarded window in our layout with the list of actual windows if(!strcmp(matchpath, "/0x*")){ //Get the list of windows int *wins = list_windows(); //Add each window to our directory listing for(int j=0; wins[j]; j++){ int win = wins[j]; char *win_string; win_string = malloc(sizeof(char)*(WID_STRING_LENGTH)); sprintf(win_string, "0x%08x", win); filler(buf, win_string, NULL, 0); free(win_string); } free(wins); } //Otherwise just add the file to our directory listing else filler(buf, matchpath+len+1, NULL, 0); } } free(matchpath); } if(!exists) return -ENOENT; //Add any extra needed elements to the directory list if(dir){ filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); }else return -ENOTDIR; return 0; } //Open a file, just check if it exists and set non seekable static int x11fs_open(const char *path, struct fuse_file_info *fi) { //Iterate through our layout size_t files_length = sizeof(x11fs_files)/sizeof(struct x11fs_file); for(size_t i=0; i<files_length; i++){ //If our file is in the layout if(!fnmatch(x11fs_files[i].path, path, FNM_PATHNAME)){ //If the path is to a window check it exists int wid; if((wid=get_winid(path)) != -1 && !exists(wid)){ return -ENOENT; } //Check if open makes sense if(x11fs_files[i].dir) return -EISDIR; fi->nonseekable=1; fi->direct_io=x11fs_files[i].direct_io; return 0; } } return -ENOENT; } //Read a file static int x11fs_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { //Iterate through our layout size_t files_length = sizeof(x11fs_files)/sizeof(struct x11fs_file); for(size_t i=0; i<files_length; i++){ //If our file is in the layout if(!fnmatch(x11fs_files[i].path, path, FNM_PATHNAME)){ //If the path is to a window check it exists int wid; if((wid=get_winid(path)) != -1 && !exists(wid)){ return -ENOENT; } //Check we can actually read if(x11fs_files[i].dir) return -EISDIR; if(!x11fs_files[i].read) return -EACCES; //Call the read function and stick the results in the buffer char *result= x11fs_files[i].read(wid); if(!result) return errno; size_t len = strlen(result); if(size > len) size = len; memcpy(buf, result, size); free(result); return size; } } return -ENOENT; } //Write to a file static int x11fs_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { //Iterate through our layout size_t files_length = sizeof(x11fs_files)/sizeof(struct x11fs_file); for(size_t i=0; i<files_length; i++){ //If our file is in the layout if(!fnmatch(x11fs_files[i].path, path, FNM_PATHNAME)){ //If the path is to a window check it exists int wid; if((wid=get_winid(path)) != -1 && !exists(wid)){ return -ENOENT; } //Check we can actually read if(x11fs_files[i].dir) return -EISDIR; if(!x11fs_files[i].write) return -EACCES; //Call the write function char *trunc_buf = strndup(buf, size); x11fs_files[i].write(wid, trunc_buf); free(trunc_buf); } } return size; } //Delete a folder (closes a window) static int x11fs_rmdir(const char *path) { //Check the folder is one representing a window //Returning ENOSYS because sometimes this will be on a dir, just not one that represents a window //TODO: Probably return more meaningful errors int wid; if((wid=get_winid(path)) == -1 || strlen(path)>11) return -ENOSYS; //Close the window close_window(wid); return 0; } //Functions for fuse to run on IO events static struct fuse_operations x11fs_operations = { .destroy = x11fs_destroy, .truncate = x11fs_truncate, .getattr = x11fs_getattr, .readdir = x11fs_readdir, .open = x11fs_open, .read = x11fs_read, .write = x11fs_write, .rmdir = x11fs_rmdir, }; //Just setup our connection to X then let fuse handle the rest int main(int argc, char **argv) { if(xcb_init()!=X11FS_SUCCESS){ fputs("Failed to setup xcb. Quiting...\n", stderr); return 1; } return fuse_main(argc, argv, &x11fs_operations, NULL); }
timgates42/x11fs
src/win_oper.h
#pragma once #include <unistd.h> char *root_width_read(int wid); char *root_height_read(int wid); void border_color_write(int wid, const char *buf); char *border_width_read(int wid); void border_width_write(int wid, const char *buf); char *geometry_width_read(int wid); void geometry_width_write(int wid, const char *buf); char *geometry_height_read(int wid); void geometry_height_write(int wid, const char *buf); char *geometry_x_read(int wid); void geometry_x_write(int wid, const char *buf); char *geometry_y_read(int wid); void geometry_y_write(int wid, const char *buf); char *mapped_read(int wid); void mapped_write(int wid, const char *buf); char *ignored_read(int wid); void ignored_write(int wid, const char *buf); void stack_write(int wid, const char *buf); char *title_read(int wid); char *class_read(int wid); char *event_read(int wid); char *focused_read(int wid); void focused_write(int wid, const char *buf);
timgates42/x11fs
src/x11fs.h
#pragma once #define WID_STRING_LENGTH 11 typedef enum {X11FS_SUCCESS, X11FS_FAILURE} X11FS_STATUS;
Alfredosavi/stm32-codes
DisplayLCD_I2C/Core/Src/liquidcrystal_i2c.c
/* * liquidcrystal_i2c.c * * Created on: Mar 14, 2022 * Author: kittm */ #include "liquidcrystal_i2c.h" extern I2C_HandleTypeDef hi2c1; uint8_t dpFunction; uint8_t dpControl; uint8_t dpMode; uint8_t dpRows; uint8_t dpBacklight; static void SendCommand(uint8_t); static void SendChar(uint8_t); static void Send(uint8_t, uint8_t); static void Write4Bits(uint8_t); static void ExpanderWrite(uint8_t); static void PulseEnable(uint8_t); static void DelayInit(void); static void DelayUS(uint32_t); uint8_t special1[8] = { 0b00000, 0b11001, 0b11011, 0b00110, 0b01100, 0b11011, 0b10011, 0b00000 }; uint8_t special2[8] = { 0b11000, 0b11000, 0b00110, 0b01001, 0b01000, 0b01001, 0b00110, 0b00000 }; void HD44780_Init(uint8_t rows) { dpRows = rows; dpBacklight = LCD_BACKLIGHT; dpFunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS; if (dpRows > 1) { dpFunction |= LCD_2LINE; } else { dpFunction |= LCD_5x10DOTS; } /* Wait for initialization */ DelayInit(); HAL_Delay(50); ExpanderWrite(dpBacklight); HAL_Delay(1000); /* 4bit Mode */ Write4Bits(0x03 << 4); DelayUS(4500); Write4Bits(0x03 << 4); DelayUS(4500); Write4Bits(0x03 << 4); DelayUS(4500); Write4Bits(0x02 << 4); DelayUS(100); /* Display Control */ SendCommand(LCD_FUNCTIONSET | dpFunction); dpControl = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; HD44780_Display(); HD44780_Clear(); /* Display Mode */ dpMode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; SendCommand(LCD_ENTRYMODESET | dpMode); DelayUS(4500); HD44780_CreateSpecialChar(0, special1); HD44780_CreateSpecialChar(1, special2); HD44780_Home(); } void HD44780_Clear() { SendCommand(LCD_CLEARDISPLAY); DelayUS(2000); } void HD44780_Home() { SendCommand(LCD_RETURNHOME); DelayUS(2000); } void HD44780_SetCursor(uint8_t col, uint8_t row) { int row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; if (row >= dpRows) { row = dpRows-1; } SendCommand(LCD_SETDDRAMADDR | (col + row_offsets[row])); } void HD44780_NoDisplay() { dpControl &= ~LCD_DISPLAYON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_Display() { dpControl |= LCD_DISPLAYON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_NoCursor() { dpControl &= ~LCD_CURSORON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_Cursor() { dpControl |= LCD_CURSORON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_NoBlink() { dpControl &= ~LCD_BLINKON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_Blink() { dpControl |= LCD_BLINKON; SendCommand(LCD_DISPLAYCONTROL | dpControl); } void HD44780_ScrollDisplayLeft(void) { SendCommand(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void HD44780_ScrollDisplayRight(void) { SendCommand(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } void HD44780_LeftToRight(void) { dpMode |= LCD_ENTRYLEFT; SendCommand(LCD_ENTRYMODESET | dpMode); } void HD44780_RightToLeft(void) { dpMode &= ~LCD_ENTRYLEFT; SendCommand(LCD_ENTRYMODESET | dpMode); } void HD44780_AutoScroll(void) { dpMode |= LCD_ENTRYSHIFTINCREMENT; SendCommand(LCD_ENTRYMODESET | dpMode); } void HD44780_NoAutoScroll(void) { dpMode &= ~LCD_ENTRYSHIFTINCREMENT; SendCommand(LCD_ENTRYMODESET | dpMode); } void HD44780_CreateSpecialChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; SendCommand(LCD_SETCGRAMADDR | (location << 3)); for (int i=0; i<8; i++) { SendChar(charmap[i]); } } void HD44780_PrintSpecialChar(uint8_t index) { SendChar(index); } void HD44780_LoadCustomCharacter(uint8_t char_num, uint8_t *rows) { HD44780_CreateSpecialChar(char_num, rows); } void HD44780_PrintStr(const char c[]) { while(*c) SendChar(*c++); } void HD44780_SetBacklight(uint8_t new_val) { if(new_val) HD44780_Backlight(); else HD44780_NoBacklight(); } void HD44780_NoBacklight(void) { dpBacklight=LCD_NOBACKLIGHT; ExpanderWrite(0); } void HD44780_Backlight(void) { dpBacklight=LCD_BACKLIGHT; ExpanderWrite(0); } static void SendCommand(uint8_t cmd) { Send(cmd, 0); } static void SendChar(uint8_t ch) { Send(ch, RS); } static void Send(uint8_t value, uint8_t mode) { uint8_t highnib = value & 0xF0; uint8_t lownib = (value<<4) & 0xF0; Write4Bits((highnib)|mode); Write4Bits((lownib)|mode); } static void Write4Bits(uint8_t value) { ExpanderWrite(value); PulseEnable(value); } static void ExpanderWrite(uint8_t _data) { uint8_t data = _data | dpBacklight; HAL_I2C_Master_Transmit(&hi2c1, DEVICE_ADDR, (uint8_t*)&data, 1, 10); } static void PulseEnable(uint8_t _data) { ExpanderWrite(_data | ENABLE); DelayUS(20); ExpanderWrite(_data & ~ENABLE); DelayUS(20); } static void DelayInit(void) { CoreDebug->DEMCR &= ~CoreDebug_DEMCR_TRCENA_Msk; CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; DWT->CTRL &= ~DWT_CTRL_CYCCNTENA_Msk; //~0x00000001; DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; //0x00000001; DWT->CYCCNT = 0; /* 3 NO OPERATION instructions */ __ASM volatile ("NOP"); __ASM volatile ("NOP"); __ASM volatile ("NOP"); } static void DelayUS(uint32_t us) { uint32_t cycles = (SystemCoreClock/1000000L)*us; uint32_t start = DWT->CYCCNT; volatile uint32_t cnt; do { cnt = DWT->CYCCNT - start; } while(cnt < cycles); }
Alfredosavi/stm32-codes
DisplayLCD_I2C/Core/Inc/liquidcrystal_i2c.h
#ifndef LIQUIDCRYSTAL_I2C_H_ #define LIQUIDCRYSTAL_I2C_H_ #include "stm32f1xx_hal.h" /* Command */ #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 /* Entry Mode */ #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 /* Display On/Off */ #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 /* Cursor Shift */ #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 /* Function Set */ #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 /* Backlight */ #define LCD_BACKLIGHT 0x08 #define LCD_NOBACKLIGHT 0x00 /* Enable Bit */ #define ENABLE 0x04 /* Read Write Bit */ #define RW 0x0 /* Register Select Bit */ #define RS 0x01 /* Device I2C Address */ #define DEVICE_ADDR (0x27 << 1) void HD44780_Init(uint8_t rows); void HD44780_Clear(); void HD44780_Home(); void HD44780_NoDisplay(); void HD44780_Display(); void HD44780_NoBlink(); void HD44780_Blink(); void HD44780_NoCursor(); void HD44780_Cursor(); void HD44780_ScrollDisplayLeft(); void HD44780_ScrollDisplayRight(); void HD44780_PrintLeft(); void HD44780_PrintRight(); void HD44780_LeftToRight(); void HD44780_RightToLeft(); void HD44780_ShiftIncrement(); void HD44780_ShiftDecrement(); void HD44780_NoBacklight(); void HD44780_Backlight(); void HD44780_AutoScroll(); void HD44780_NoAutoScroll(); void HD44780_CreateSpecialChar(uint8_t, uint8_t[]); void HD44780_PrintSpecialChar(uint8_t); void HD44780_SetCursor(uint8_t, uint8_t); void HD44780_SetBacklight(uint8_t new_val); void HD44780_LoadCustomCharacter(uint8_t char_num, uint8_t *rows); void HD44780_PrintStr(const char[]); #endif /* LIQUIDCRYSTAL_I2C_H_ */
aposteriorist/dmd
test/compilable/test22842.c
// https://issues.dlang.org/show_bug.cgi?id=22842 /*******************************/ typedef int (myfunc)(); myfunc fun; /*******************************/ int town(); typedef int (funky)(); funky town; /*******************************/ typedef int (mudd)(); static mudd ville; int job() { return ville(); } int ville() // inherits "static" from declaration. { return 0; } /*******************************/ typedef int (skyy)(); void high() { skyy asdf; } /*******************************/ void low() { typedef int (down)(); } typedef int down; down dd; int low2() { dd = 1; }
gk969/CryptoDemo
heap.h
<gh_stars>1-10 #ifndef HEAP_H #define HEAP_H #include <stdint.h> void heap_init(uint32_t* heap_buf, uint32_t len); void alloc_test(); void* heap_alloc(uint32_t size); void heap_free(void* p); #endif
gk969/CryptoDemo
utils.h
<filename>utils.h<gh_stars>1-10 #pragma once #pragma warning(disable : 4996) typedef unsigned int u32; typedef unsigned long int u64; time_t str_to_time(const char* str); int time_to_str(time_t time, char* buf, int size); char* time_to_str(time_t time); int now_to_str(char* buf, int size); char* now_to_str(); void open_log_file(const char* file_path); void close_log_file(); void log_str(const char* str); void log(const char* pcString, ...); void log_ln(const char* pcString, ...); void log_hex(void* data, int len);
gk969/CryptoDemo
rsa.h
/***************************************************************************** Filename : rsa.h Author : Terrantsh (<EMAIL>) Date : 2018-9-20 11:22:22 Description : RSA加密头文件 *****************************************************************************/ #ifndef __RSA_H__ #define __RSA_H__ #include <stdint.h> extern uint8_t KEY_EXPONENT[3]; #define KEY_M_BITS 2048 // RSA key lengths #define RSA_MAX_MODULUS_BITS KEY_M_BITS #define RSA_MAX_MODULUS_LEN ((RSA_MAX_MODULUS_BITS + 7) / 8) #define RSA_MAX_PRIME_BITS ((RSA_MAX_MODULUS_BITS + 1) / 2) #define RSA_MAX_PRIME_LEN ((RSA_MAX_PRIME_BITS + 7) / 8) // Error codes #define ERR_WRONG_DATA 0x1001 #define ERR_WRONG_LEN 0x1002 typedef uint64_t dbn_t; typedef uint32_t bn_t; int rsa_public_encrypt(uint8_t* pub_key, uint8_t* in, uint32_t in_len, uint8_t* rand, uint8_t* out, uint32_t* heap_buf); #endif // __RSA_H__
gk969/CryptoDemo
aes_128.h
/* * FileName : AES.h * */ #ifndef __AES_H__ #define __AES_H__ class AES_128 { public: void SetKey(unsigned char* key); unsigned char* Cipher(const unsigned char* input, unsigned char* output); unsigned char* InvCipher(const unsigned char* input, unsigned char* output); void* Cipher(const void* input, void* output, int length = 0); void* InvCipher(const void* input, void* output, int length); private: unsigned char w[11][4][4]; void KeyExpansion(unsigned char* key); unsigned char FFmul(unsigned char a, unsigned char b); void SubBytes(unsigned char state[][4]); void ShiftRows(unsigned char state[][4]); void MixColumns(unsigned char state[][4]); void AddRoundKey(unsigned char state[][4], unsigned char k[][4]); void InvSubBytes(unsigned char state[][4]); void InvShiftRows(unsigned char state[][4]); void InvMixColumns(unsigned char state[][4]); }; #define ONLY_CFB class AES_128_cfb { private: AES_128 m_aes; public: void set_key(unsigned char* key); int Encrypt(unsigned char* iv, const unsigned char* input, int length, unsigned char* output); int Decrypt(unsigned char* iv, const unsigned char* input, int length, unsigned char* output); }; #endif
gk969/CryptoDemo
keys.h
#include <stdint.h> #define KEY_M_BITS 2048 // KEY_2048 uint8_t key_m[] = { 0xB0, 0x1D, 0x83, 0x85, 0x23, 0x65, 0x20, 0xC6, 0xBD, 0x10, 0xE6, 0x38, 0xEF, 0x74, 0xF5, 0xF3, 0x6C, 0xD1, 0xD1, 0x07, 0x2F, 0x3E, 0xD8, 0xAA, 0x9C, 0xE2, 0xC6, 0x22, 0x32, 0x6E, 0x5B, 0x58, 0xFF, 0x7E, 0x2B, 0x97, 0xE8, 0x2F, 0xE9, 0xD9, 0x88, 0x3F, 0xD5, 0x0B, 0x9E, 0x36, 0x6F, 0xAF, 0x47, 0x0C, 0xD8, 0xFC, 0x80, 0xB6, 0x58, 0x78, 0x4E, 0x0C, 0x9C, 0x96, 0x81, 0xFC, 0xFA, 0x5D, 0x06, 0x0A, 0xEA, 0xA5, 0x93, 0x25, 0x0B, 0x02, 0x9C, 0x63, 0xFC, 0xB7, 0xA5, 0x49, 0xB0, 0xDB, 0x9F, 0x37, 0x10, 0x97, 0x01, 0xBE, 0xAD, 0xFB, 0x3F, 0x6D, 0x99, 0xC4, 0xCB, 0x62, 0x6D, 0x88, 0x9B, 0x7C, 0xE2, 0xEB, 0x24, 0x20, 0x06, 0xA8, 0x2B, 0x04, 0xA1, 0xB9, 0xCE, 0x5F, 0x20, 0xF7, 0x0C, 0x57, 0x6F, 0x34, 0xF4, 0xFC, 0xF0, 0xB2, 0x95, 0x5A, 0x1F, 0x81, 0x5D, 0xA9, 0x54, 0x7B, 0x7F, 0x82, 0x67, 0x34, 0x5D, 0xD0, 0x7C, 0xC7, 0x67, 0xEF, 0x58, 0x4F, 0x2E, 0x5C, 0x42, 0x2A, 0xDB, 0xD6, 0x8B, 0xB6, 0x2D, 0xF7, 0x87, 0x33, 0x6B, 0xE4, 0x84, 0x19, 0xA2, 0x76, 0x8C, 0xC9, 0x64, 0x76, 0x1F, 0xE9, 0x78, 0xF3, 0xAA, 0x6C, 0x5A, 0xC5, 0x6D, 0x9E, 0x05, 0x40, 0xE0, 0x9D, 0x67, 0x7C, 0xC8, 0x10, 0x07, 0x31, 0x53, 0xA7, 0xC8, 0xDF, 0xB6, 0xA4, 0xFB, 0xF2, 0x6C, 0x39, 0xDB, 0x0A, 0xB6, 0x91, 0x42, 0x52, 0x26, 0x53, 0xFB, 0xD6, 0x37, 0xE7, 0xE9, 0x23, 0xA2, 0xCD, 0xB1, 0x38, 0x2B, 0x49, 0x05, 0xA1, 0x66, 0x85, 0x52, 0x96, 0xD3, 0xA2, 0xCD, 0x01, 0x85, 0x87, 0xE4, 0xEE, 0x8F, 0xFB, 0xF0, 0xA6, 0x67, 0x75, 0x1E, 0xB8, 0x32, 0x71, 0xAA, 0x36, 0x40, 0x4F, 0x9F, 0xFD, 0xDB, 0x90, 0x10, 0xC4, 0x84, 0xB8, 0x59, 0x9D, 0xEE, 0xB0, 0x46, 0x85, 0x57, 0xE7 }; uint8_t key_e[] = { 0x01, 0x00, 0x01}; //65537 uint8_t key_pe[] = { 0x67, 0xbf, 0xc8, 0x3e, 0x2a, 0x95, 0x12, 0xa0, 0xd3, 0xd7, 0x44, 0x74, 0x75, 0x14, 0x07, 0xd3, 0x36, 0xdc, 0x2e, 0xe1, 0xf1, 0x03, 0xdb, 0xaf, 0xe5, 0x99, 0x7b, 0xe0, 0xae, 0x42, 0x48, 0x03, 0xf5, 0xc5, 0x61, 0xf6, 0xb6, 0x73, 0xe6, 0x85, 0x3d, 0x5a, 0x34, 0x16, 0xc6, 0xb7, 0xf2, 0x0c, 0xfe, 0x44, 0x08, 0x96, 0x64, 0x8c, 0x28, 0x8d, 0xde, 0x96, 0xa8, 0x51, 0xe9, 0x4e, 0x37, 0xa3, 0x36, 0xc7, 0x09, 0x59, 0x73, 0x1a, 0xa6, 0x0f, 0x14, 0x9a, 0xf2, 0x35, 0x1a, 0x7a, 0xbd, 0xec, 0x98, 0x5b, 0xf7, 0x9d, 0xde, 0x20, 0xe2, 0xff, 0xaa, 0xeb, 0x0f, 0x89, 0x08, 0xa4, 0x6e, 0x06, 0x07, 0xa7, 0xe1, 0xf1, 0x86, 0xc0, 0x7a, 0x7f, 0x16, 0x1a, 0xbe, 0xa8, 0xd8, 0x16, 0x36, 0x6e, 0xdd, 0x81, 0x76, 0x92, 0xd1, 0x79, 0xfc, 0x49, 0x41, 0xcc, 0x3e, 0xdb, 0x5b, 0xe3, 0xd4, 0x91, 0x62, 0xfa, 0x26, 0x04, 0x1b, 0x1f, 0x5e, 0x2b, 0xd4, 0x7c, 0xb2, 0x68, 0x5c, 0xec, 0x40, 0xf2, 0xc6, 0xe2, 0x83, 0x7d, 0x71, 0xe0, 0xf9, 0xfa, 0x41, 0x24, 0x8d, 0x36, 0x1c, 0xe8, 0xc4, 0x05, 0x38, 0xab, 0x23, 0x37, 0xd1, 0xc8, 0xc6, 0xad, 0xe5, 0xde, 0x98, 0xd5, 0x0a, 0x7e, 0xaa, 0xba, 0x54, 0x5a, 0x63, 0xd5, 0xe1, 0x49, 0xbe, 0x84, 0x0d, 0xde, 0x66, 0x71, 0x78, 0xc8, 0xdf, 0x5c, 0x53, 0x88, 0xea, 0x00, 0xc1, 0x8d, 0xaf, 0x81, 0x9f, 0x0a, 0xc4, 0xa0, 0x6e, 0xb0, 0xf7, 0xda, 0xa1, 0x22, 0x72, 0x46, 0x65, 0x68, 0x3b, 0x24, 0xb7, 0x89, 0xd0, 0xce, 0xde, 0x3a, 0xf3, 0xd5, 0x07, 0x94, 0xd7, 0x17, 0x9c, 0xc7, 0x90, 0x77, 0x7b, 0x6c, 0x7a, 0x21, 0x72, 0xe5, 0x17, 0x25, 0x8a, 0x84, 0x20, 0x01, 0x1b, 0x9b, 0xe5, 0x96, 0x5c, 0x17, 0x0b, 0xde, 0x85, 0x38, 0xcf, 0x95}; uint8_t key_p1[] = { 0xdf, 0xd1, 0x18, 0x63, 0x6f, 0x2c, 0x1b, 0x14, 0x3b, 0x95, 0x3d, 0x56, 0xdd, 0x5b, 0x6f, 0x01, 0x6e, 0xf9, 0x4c, 0x2b, 0xcb, 0xeb, 0xdd, 0x89, 0xb0, 0x8e, 0xdd, 0xf3, 0xf0, 0x0f, 0xf7, 0x71, 0x75, 0xd0, 0x7e, 0xb0, 0xbe, 0x6b, 0x51, 0x3a, 0x8c, 0xcf, 0x9b, 0x81, 0xfa, 0x34, 0x4f, 0xfc, 0x98, 0xd6, 0x65, 0xb1, 0x2f, 0x82, 0x55, 0xa8, 0xd1, 0xb5, 0x1a, 0xaf, 0x7b, 0xda, 0x6f, 0x02, 0x43, 0x14, 0x7e, 0x69, 0x52, 0x11, 0x9e, 0xa9, 0x95, 0x44, 0xb1, 0x19, 0x7f, 0x7b, 0x7c, 0x67, 0x30, 0x11, 0x67, 0x88, 0x9d, 0xb1, 0xb5, 0x6e, 0x6a, 0x69, 0x17, 0x64, 0x57, 0xdc, 0x5e, 0xfd, 0x33, 0xae, 0x84, 0xdc, 0x2a, 0x73, 0x54, 0x8d, 0xbe, 0x04, 0xc7, 0x6f, 0x6e, 0x7f, 0x31, 0xf1, 0x04, 0xb3, 0x6b, 0xf7, 0x9f, 0x62, 0x15, 0xb0, 0x75, 0x12, 0xa8, 0x4f, 0x02, 0x4a, 0xcb, 0xd7}; uint8_t key_p2[] = { 0xd2, 0x5b, 0x6c, 0x9d, 0xa4, 0x9b, 0xa9, 0x6e, 0x29, 0x67, 0x3f, 0xd1, 0xc2, 0x53, 0x1a, 0x50, 0x5b, 0x0a, 0x7c, 0xc1, 0x64, 0x01, 0xff, 0x20, 0x20, 0x8c, 0x68, 0x32, 0xb1, 0x1a, 0xfb, 0x8e, 0x73, 0x54, 0x29, 0x3b, 0xe7, 0xfc, 0x94, 0x0f, 0x63, 0x06, 0xa2, 0x87, 0x56, 0xa4, 0xe3, 0x48, 0x75, 0x21, 0xb7, 0x10, 0x97, 0xfc, 0x3a, 0x1d, 0xb3, 0xe2, 0xab, 0xe6, 0x4b, 0x04, 0x8d, 0xde, 0xfb, 0xac, 0xd3, 0xe4, 0x3d, 0x71, 0x20, 0xda, 0x04, 0xaa, 0xe2, 0x98, 0xf4, 0xe3, 0x6c, 0xf4, 0xfa, 0xc3, 0xa7, 0x1f, 0x73, 0x30, 0x4f, 0x3c, 0xfe, 0x8a, 0x3e, 0x21, 0x06, 0xe7, 0x02, 0xb4, 0xe5, 0x9d, 0x4e, 0x37, 0x64, 0x67, 0x15, 0xf3, 0x64, 0x73, 0xcf, 0x30, 0x2d, 0x54, 0x19, 0x76, 0x22, 0xee, 0x44, 0xb5, 0xcb, 0x8f, 0x94, 0xa0, 0xf5, 0x15, 0x91, 0x68, 0x56, 0xcc, 0x38, 0x1b}; uint8_t key_e1[] = { 0x7e, 0x33, 0xcf, 0x06, 0xb2, 0x77, 0x32, 0x45, 0xb4, 0x5b, 0x30, 0x9d, 0x3c, 0x70, 0x04, 0x25, 0xd0, 0xc7, 0x6d, 0xb5, 0xfc, 0x64, 0x61, 0x24, 0xf4, 0x93, 0x7a, 0x7f, 0xc4, 0x4b, 0x9c, 0x81, 0x33, 0xa7, 0x7e, 0xe8, 0x76, 0x56, 0xd9, 0x14, 0xa4, 0xb5, 0xa3, 0xc0, 0x24, 0xaf, 0x3e, 0xb2, 0xf6, 0x13, 0x5e, 0x80, 0x0c, 0x83, 0xf7, 0x7d, 0x1b, 0xd2, 0x7c, 0xdb, 0x9a, 0x80, 0xce, 0xbb, 0x7d, 0xcb, 0x9e, 0x84, 0x10, 0xac, 0xb2, 0xc4, 0x78, 0xd0, 0xa4, 0xf3, 0xf5, 0xb8, 0x51, 0xab, 0x75, 0xa5, 0x3a, 0xb6, 0x04, 0x05, 0x62, 0x82, 0x82, 0x2a, 0x03, 0xf0, 0xa6, 0xc2, 0x32, 0x25, 0x9f, 0xf0, 0xb6, 0x25, 0xd7, 0x21, 0xf4, 0xf9, 0x7f, 0xbd, 0xfe, 0x1e, 0xcd, 0x35, 0x97, 0x99, 0x89, 0xc7, 0x0a, 0x08, 0x34, 0xad, 0x00, 0x01, 0xe1, 0xe1, 0xc5, 0x59, 0xd7, 0xb7, 0x09, 0x3d}; uint8_t key_e2[] = { 0x87, 0xf8, 0xa4, 0x9a, 0xb9, 0x9e, 0x0c, 0xc4, 0xb2, 0x6a, 0x94, 0xec, 0x07, 0x4a, 0x24, 0x46, 0x30, 0xb2, 0xf4, 0xb5, 0x24, 0xe9, 0xcd, 0x79, 0x7c, 0xd0, 0x85, 0x41, 0xcf, 0x0c, 0xfb, 0xf1, 0xb6, 0x46, 0x7e, 0x68, 0xc4, 0xa9, 0x95, 0x22, 0xe5, 0x05, 0x92, 0xe5, 0x1c, 0x72, 0x74, 0x9f, 0x8f, 0x66, 0xfd, 0xa7, 0xf2, 0x36, 0x0d, 0x72, 0xc9, 0xa6, 0x09, 0x2b, 0x50, 0xee, 0x5e, 0xad, 0xf5, 0xcc, 0x5f, 0x22, 0xb7, 0x3c, 0x7a, 0xd9, 0xb2, 0x0e, 0xab, 0x6d, 0xe7, 0x4d, 0x62, 0x4e, 0x70, 0x11, 0x2b, 0xe3, 0xbe, 0x57, 0x49, 0xc0, 0xc9, 0x5f, 0x9e, 0x8d, 0x46, 0xa2, 0xe8, 0x32, 0xfa, 0x00, 0xd6, 0x60, 0x23, 0xbc, 0x26, 0x8a, 0x2f, 0x32, 0x54, 0x88, 0x75, 0xa4, 0x58, 0xd8, 0xed, 0xf7, 0x49, 0xde, 0xa0, 0xf7, 0xec, 0x40, 0xa6, 0x6b, 0x0c, 0x94, 0x7f, 0x16, 0x7e, 0x65}; uint8_t key_c[] = { 0x46, 0x53, 0x1a, 0x19, 0x21, 0x2d, 0xfe, 0x36, 0x73, 0x85, 0x3a, 0x71, 0xa2, 0x84, 0xfa, 0x5c, 0x35, 0x76, 0xdb, 0x10, 0xf0, 0x34, 0x86, 0x14, 0xa9, 0x70, 0x1c, 0xd8, 0x73, 0xdf, 0x2b, 0xd0, 0x43, 0xd9, 0x73, 0xd2, 0x26, 0x1f, 0xb2, 0xba, 0x9d, 0x82, 0x57, 0x9b, 0x4c, 0xcd, 0x4a, 0xbc, 0xf2, 0x1f, 0xfa, 0xf5, 0x5b, 0x2a, 0x8d, 0x6c, 0x20, 0x39, 0xdb, 0xf8, 0x55, 0x19, 0x11, 0x15, 0xb4, 0xa9, 0xa1, 0x00, 0xdc, 0x93, 0x31, 0x53, 0xc5, 0xc6, 0x17, 0xcb, 0x36, 0xe9, 0x00, 0xd8, 0x6e, 0xc8, 0x75, 0x69, 0x6a, 0x85, 0x4d, 0x42, 0x01, 0x2a, 0x86, 0x36, 0x59, 0xfc, 0xd7, 0x0b, 0x57, 0x8a, 0x76, 0x7d, 0xc0, 0xbc, 0x43, 0x8a, 0x4d, 0xb1, 0x14, 0x07, 0x4d, 0x28, 0x5a, 0xec, 0x30, 0x28, 0x93, 0x6e, 0x68, 0x14, 0x1a, 0xc0, 0x17, 0x6c, 0xe1, 0x7c, 0x39, 0x19, 0xe6, 0xd8}; // END
gk969/CryptoDemo
bignum.h
/***************************************************************************** Filename : bignum.h Author : Terrantsh (<EMAIL>) Date : 2018-9-20 11:23:45 Description : *****************************************************************************/ #ifndef __BIGNUM_H__ #define __BIGNUM_H__ #include <stdint.h> typedef uint64_t dbn_t; typedef uint32_t bn_t; #define BN_DIGIT_BITS 32 // For uint32_t #define BN_MAX_DIGITS 65 // RSA_MAX_MODULUS_LEN + 1 #define BN_MAX_DIGIT 0xFFFFFFFF #define DIGIT_2MSB(x) (uint32_t)(((x) >> (BN_DIGIT_BITS - 2)) & 0x03) void bn_decode(bn_t *bn, uint32_t digits, uint8_t *hexarr, uint32_t size); void bn_encode(uint8_t *hexarr, uint32_t size, bn_t *bn, uint32_t digits); void bn_assign(bn_t *a, bn_t *b, uint32_t digits); // a = b void bn_assign_zero(bn_t *a, uint32_t digits); // a = 0 bn_t bn_add(bn_t *a, bn_t *b, bn_t *c, uint32_t digits); // a = b + c, return carry bn_t bn_sub(bn_t *a, bn_t *b, bn_t *c, uint32_t digits); // a = b - c, return borrow void bn_mul(bn_t *a, bn_t *b, bn_t *c, uint32_t digits); // a = b * c void bn_div(bn_t *a, bn_t *b, bn_t *c, uint32_t cdigits, bn_t *d, uint32_t ddigits); // a = b / c, d = b % c bn_t bn_shift_l(bn_t *a, bn_t *b, uint32_t c, uint32_t digits); // a = b << c (a = b * 2^c) bn_t bn_shift_r(bn_t *a, bn_t *b, uint32_t c, uint32_t digits); // a = b >> c (a = b / 2^c) void bn_mod(bn_t *a, bn_t *b, uint32_t bdigits, bn_t *c, uint32_t cdigits); // a = b mod c void bn_mod_mul(bn_t *a, bn_t *b, bn_t *c, bn_t *d, uint32_t digits); // a = b * c mod d void bn_mod_exp(bn_t *a, bn_t *b, bn_t *c, uint32_t cdigits, bn_t *d, uint32_t ddigits); // a = b ^ c mod d int bn_cmp(bn_t *a, bn_t *b, uint32_t digits); // returns sign of a - b uint32_t bn_digits(bn_t *a, uint32_t digits); // returns significant length of a in digits #define BN_ASSIGN_DIGIT(a, b, digits) {bn_assign_zero(a, digits); a[0] = b;} #endif // __BIGNUM_H__
gk969/CryptoDemo
md5.h
<reponame>gk969/CryptoDemo<gh_stars>1-10 #ifndef MD5_H #define MD5_H #define MD5_SIZE 16 unsigned char* MD5_Compute(unsigned char* md5_buf, unsigned char* data, unsigned int len); #endif
luca1337/LinkedLists
TreeDataStructure/LinkedListSingle.h
#pragma once #include <iostream> #include <string> #include <time.h> #include "LinkedListNode.h" #define CHECK_ERROR(x) if(!x)\ {\ std::cout << "no elemts were found in the list" << std::endl;\ return;\ }\ #define CHECK_ERROR_RET(x) if(!x)\ {\ std::cout << "no elemts were found in the list" << std::endl;\ return nullptr;\ }\ template <class T> class LinkedListSingle { public: LinkedListSingle(); ~LinkedListSingle(); LinkedListNode<T>* AddAfter(LinkedListNode<T>* node, T elem); void AddAfter(LinkedListNode<T>* node, LinkedListNode<T>* newNode); LinkedListNode<T>* AppendLast(T elem); void AppendLast(LinkedListNode<T>* node); LinkedListNode<T>* AppendFirst(T elem); void AppendFirst(LinkedListNode<T>* node); LinkedListNode<T>* Find(T elem); LinkedListNode<T>* Reverse(); LinkedListSingle<T> Shuffle(); void Sort(bool(*Cmp)(void*, void*)); void Remove(T elem); void Remove(LinkedListNode<T> node); void RemoveFirst(); void RemoveLast(); void Traverse(); LinkedListNode<T>* First() const; LinkedListNode<T>* Last() const; unsigned Size(); private: static bool CompareElements(void* left, void* right) { return left > right; } LinkedListNode<T>* Head; LinkedListNode<T>* Tail; unsigned Count; }; template<class T> inline LinkedListSingle<T>::LinkedListSingle() { this->Head = nullptr; this->Tail = nullptr; this->Count = 1; } template<class T> inline LinkedListSingle<T>::~LinkedListSingle() { } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::AddAfter(LinkedListNode<T>* node, T elem) { LinkedListNode<T>* FoundNode = this->Find(node->Data); LinkedListNode<T>* Temp = new LinkedListNode<int>(elem); LinkedListNode<T>* OldNode = new LinkedListNode<int>(); Temp->Data = elem; CHECK_ERROR_RET(FoundNode); if (FoundNode == this->Head && FoundNode == this->Tail) { FoundNode->Next = Temp; this->Tail = Temp; } if (FoundNode == this->Tail) { Tail->Next = Temp; this->Tail = Temp; } else if (FoundNode == this->Head) { OldNode = this->Head->Next; this->Head->Next = Temp; Temp->Next = OldNode; delete OldNode; OldNode = nullptr; } else { Temp->Next = FoundNode->Next; FoundNode->Next = Temp; } this->Count++; return Temp; } template<class T> inline void LinkedListSingle<T>::AddAfter(LinkedListNode<T>* node, LinkedListNode<T>* newNode) { LinkedListNode<T>* FoundNode = this->Find(node->Data); LinkedListNode<T>* OldNode = new LinkedListNode<int>(); if (!FoundNode) { std::cout << "no elemts were found in the list" << std::endl; return; } if (FoundNode == this->Head && FoundNode == this->Tail) { FoundNode->Next = newNode; this->Tail = newNode; } if (FoundNode == this->Tail) { Tail->Next = newNode; this->Tail = newNode; } else if (FoundNode == this->Head) { OldNode = this->Head->Next; this->Head->Next = newNode; newNode->Next = OldNode; delete OldNode; OldNode = nullptr; } else { newNode->Next = FoundNode->Next; FoundNode->Next = newNode; } this->Count++; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::AppendLast(T elem) { LinkedListNode<T>* TempItem = new LinkedListNode<T>(elem); //create a temp item and check if the head is null, if the head is null //means we have no items inside the list so it's empty //TempItem->Next = nullptr; //if the head is null it means this is the first element to be added inside that list //this first item is both head and both tail! //-------------------------------------------------- // head-> |0| <-tail (the first item is both t,h) //-------------------------------------------------- if (this->Head == nullptr) { this->Head = TempItem; this->Tail = TempItem; return TempItem; } else { //if the head is not null, it means we already have 1 element inside that list //all we need to do is adda new element next to the previous one //------------------------------------------------------------------- //head-> |0|0| <- tail(head is the last element to be added, tail is the first one we added) //------------------------------------------------------------------- this->Tail->Next = TempItem; this->Tail = TempItem; } this->Count++; return TempItem; } template<class T> inline void LinkedListSingle<T>::AppendLast(LinkedListNode<T>* node) { if (!this->Head) { this->Head = node; this->Tail = node; } else { this->Tail->Next = node; this->Tail = node; } this->Count++; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::AppendFirst(T elem) { LinkedListNode<T>* TempItem = new LinkedListNode<T>(elem); //the first added element of the list will always be the tail if (!this->Head) { this->Head = TempItem; this->Tail = TempItem; return TempItem; } else { //if thre is already at least 1 element we need to appent it before that element.. //so the current head will become the new tail and the new element will become the new head // head-> |0|0| <-tail TempItem->Next = this->Head; this->Head = TempItem; } this->Count++; return TempItem; } template<class T> inline void LinkedListSingle<T>::AppendFirst(LinkedListNode<T>* node) { if (!this->Head) { this->Head = node; this->Tail = node; } else { //if thre is already at least 1 element we need to appent it before that element.. //so the current head will become the new tail and the new element will become the new head // head-> |0|0| <-tail node->Next = this->Head; this->Head = node; } this->Count++; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::Find(T elem) { if (!this->Head && !this->Tail) { std::cout << "list is empty" << std::endl; } LinkedListNode<T>* Temp = new LinkedListNode<T>(); Temp = this->Head; while (Temp) { if (Temp->Data == elem) { return Temp; } Temp = Temp->Next; } return nullptr; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::Reverse() { LinkedListNode<T>* Prev = nullptr; while (this->Head->Next) { LinkedListNode<T>* Next = this->Head->Next; this->Head->Next = Prev; Prev = Head; this->Head = Next; } this->Head->Next = Prev; return this->Head; } template<class T> inline LinkedListSingle<T> LinkedListSingle<T>::Shuffle() { //todo: implement shuffle LinkedListSingle<T> Temp; srand((unsigned)time(NULL)); for (unsigned int i = 0; i < this->Count; i++) { unsigned int random = (unsigned int)(((double)rand() / RAND_MAX) * this->Count); std::cout << "rand num: " << random << std::endl; } return Temp; } template<class T> inline void LinkedListSingle<T>::Sort(bool(*Cmp)(void*, void*)) { if (this->Count < 1) return; if (!Cmp) Cmp = this->CompareElements; LinkedListNode<T>* First = this->Head; while (this->Count-- > 0) { if (First->Next == nullptr) break; for (unsigned i = 0; i < this->Count; i++) { if (this->CompareElements((void*)First->Data, (void*)First->Next->Data)) { T Elem = First->Data; First->Data = First->Next->Data; First->Next->Data = Elem; } First = First->Next; } First = this->Head; } } template<class T> inline void LinkedListSingle<T>::Remove(T elem) { LinkedListNode<T>* ToFind = this->Find(elem); LinkedListNode<T>* Temp = new LinkedListNode<T>(); LinkedListNode<T>* Iter = new LinkedListNode<T>(); if (!ToFind) { std::cout << "could not find the specified element.." << std::endl; return; } if (ToFind == this->Head && ToFind == this->Tail) { this->Head = nullptr; std::cout << "all elements have been removed" << std::endl; } else { if (ToFind != this->Head && ToFind != this->Tail) { Temp = ToFind->Next; Iter = this->Head; while (Iter) { if (Iter->Next == ToFind) { Iter->Next = nullptr; break; } Iter = Iter->Next; } Iter->Next = ToFind->Next; } else if (ToFind == this->Head) { Temp = this->Head->Next; this->Head = nullptr; this->Head = Temp; } else if (this->Head->Next != this->Tail) { Temp = this->Tail; this->Head = nullptr; this->Head = Temp; } else if (this->Head->Next == ToFind && ToFind == this->Tail) { this->RemoveLast(); } else if (ToFind == this->Tail && ToFind == this->Head) { this->Head = nullptr; this->Tail = nullptr; } } this->Count--; } template<class T> inline void LinkedListSingle<T>::Remove(LinkedListNode<T> node) { LinkedListNode<T>* Temp = new LinkedListNode<T>(); LinkedListNode<T>* Iter = new LinkedListNode<T>(); if (!node) { std::cout << "could not find the specified element.." << std::endl; return; } if (node == this->Head && node == this->Tail) { this->Head = nullptr; std::cout << "all elements have been removed" << std::endl; } else { if (node != this->Head && node != this->Tail) { Temp = node->Next; Iter = this->Head; while (Iter) { if (Iter->Next == node) { Iter->Next = nullptr; break; } Iter = Iter->Next; } Iter->Next = node->Next; } else if (node == this->Head) { Temp = this->Head->Next; this->Head = nullptr; this->Head = this->Temp; } else if (node == this->Tail) { Temp = this->Tail; this->Head = nullptr; this->Head = this->Temp; } } this->Count--; } template<class T> inline void LinkedListSingle<T>::RemoveFirst() { LinkedListNode<T>* Temp = new LinkedListNode<T>(); if (!this->Head && !this->Tail) { std::cout << "no elements in list" << std::endl; return; } Temp = this->Head->Next; delete this->Head; this->Head = nullptr; this->Head = Temp; delete Temp; this->Count--; } template<class T> inline void LinkedListSingle<T>::RemoveLast() { LinkedListNode<T>* CurrNode = new LinkedListNode<T>(); LinkedListNode<T>* PrevNode = new LinkedListNode<T>(); CurrNode = this->Head; while (CurrNode->Next) { PrevNode = CurrNode; CurrNode = CurrNode->Next; } this->Tail = PrevNode; PrevNode->Next = nullptr; delete CurrNode; this->Count--; } template<class T> inline void LinkedListSingle<T>::Traverse() { LinkedListNode<T>* Temp = new LinkedListNode<T>(); Temp = this->Head; //head is first element std::cout << "------START--------" << std::endl; std::cout << "Head: " << this->Head->Data << std::endl; std::cout << "Tail: " << this->Tail->Data << std::endl; std::cout << "" << std::endl; // head-> |0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|.. <-tail //starting from tail we iterate the list until the "next" is nullptr while (Temp != nullptr) { std::cout << "Data: " << Temp->Data << std::endl; Temp = Temp->Next; } std::cout << "------END--------" << std::endl; std::cout << "" << std::endl; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::First() const { return this->Head; } template<class T> inline LinkedListNode<T>* LinkedListSingle<T>::Last() const { return this->Tail; } template<class T> inline unsigned LinkedListSingle<T>::Size() { return this->Count; }
luca1337/LinkedLists
LinkedListDouble/Node.h
#pragma once #include <iostream> template <class T> struct Node { T Data; Node* Next; Node* Prev; Node(); Node(T elem); }; template<class T> inline Node<T>::Node() { this->Data = NULL; this->Next = nullptr; this->Prev = nullptr; } template<class T> inline Node<T>::Node(T elem) { this->Data = elem; this->Next = nullptr; this->Prev = nullptr; }
luca1337/LinkedLists
LinkedListDouble/LinkedList.h
#pragma once #include "Node.h" #include <iostream> #include <string> template <class T> class LinkedList { public: LinkedList(); LinkedList(const LinkedList<T>& other); LinkedList(LinkedList<T>&& other) noexcept; LinkedList<T>& operator=(LinkedList<T>&& other); Node<T>* AddAfter(Node<T>* node, T elem); void AddAfter(Node<T>* node, Node<T>* newNode); Node<T>* AddBefore(Node<T>* node, T elem); void AddBefore(Node<T>* node, Node<T>* newNode); Node<T>* AppendFirst(T elem); void AppendFirst(Node<T>* node); Node<T>* AppendLast(T elem); void AppendLast(Node<T>* node); Node<T>* Find(T elem); void Traverse(); void TraverseReverse(); private: Node<T>* Head; Node<T>* Tail; int Count; }; template<class T> inline LinkedList<T>::LinkedList() { this->Head = nullptr; this->Tail = nullptr; this->Count = 1; } template<class T> inline LinkedList<T>::LinkedList(const LinkedList<T>& other) { Node<T>* TempHead = other.Head; while (TempHead != nullptr) { this->AppendLast(TempHead->Data); TempHead = TempHead->Next; } } template<class T> inline LinkedList<T>::LinkedList(LinkedList<T>&& other) noexcept { Node<T>* TempHead = other.Head; std::cout << "move ctor called" << std::endl; while (TempHead != nullptr) { std::move(this->AppendLast(TempHead->Data)); TempHead = TempHead->Next; } } template<class T> inline LinkedList<T>& LinkedList<T>::operator=(LinkedList<T>&& other) { // TODO: inserire l'istruzione return qui Node<T>* TempHead = other.Head; std::cout << "move ass called" << std::endl; while (TempHead != nullptr) { std::move(this->AppendLast(TempHead->Data)); TempHead->Prev = nullptr;; TempHead = TempHead->Next; } return *this; } template<class T> inline Node<T>* LinkedList<T>::AddAfter(Node<T>* node, T elem) { Node<T>* ToFind = this->Find(node->Data); Node<T>* NewNode = new Node<T>(elem); Node<T>* Temp = new Node<T>(); if (!this->Head) { this->Head = NewNode; this->Tail = NewNode; this->Head->Next = this->Tail; this->Tail->Prev = this->Head; } if (ToFind == this->Tail) { this->Tail->Next = NewNode; NewNode->Prev = this->Tail; this->Tail = NewNode; return NewNode; } else { Temp = ToFind->Next; ToFind->Next = NewNode; NewNode->Next = Temp; Temp->Prev = NewNode; NewNode->Prev = ToFind; return NewNode; } } template<class T> inline void LinkedList<T>::AddAfter(Node<T>* node, Node<T>* newNode) { Node<T>* ToFind = this->Find(node->Data); Node<T>* Temp = new Node<T>(); if (!this->Head) { this->Head = NewNode; this->Tail = NewNode; this->Head->Next = this->Tail; this->Tail->Prev = this->Head; } if (ToFind == this->Tail) { this->Tail->Next = newNode; newNode->Prev = this->Tail; this->Tail = newNode; } else { Temp = ToFind->Next; ToFind->Next = newNode; newNode->Next = Temp; Temp->Prev = newNode; newNode->Prev = ToFind; } } template<class T> inline Node<T>* LinkedList<T>::AddBefore(Node<T>* node, T elem) { Node<T>* ToFind = this->Find(node->Data); Node<T>* ToAdd = new Node<T>(elem); Node<T>* Temp = new Node<T>(); if (ToFind == this->Head) //adding before head { Temp = this->Head; this->Head->Prev = ToAdd; this->Head = ToAdd; ToAdd->Next = Temp; } else // in any other situation { Temp = ToFind->Prev; ToFind->Prev = ToAdd; ToAdd->Next = ToFind; Temp->Next = ToAdd; ToAdd->Prev = Temp; } return ToAdd; } template<class T> inline void LinkedList<T>::AddBefore(Node<T>* node, Node<T>* newNode) { } template<class T> inline Node<T>* LinkedList<T>::AppendFirst(T elem) { return NULL; } template<class T> inline void LinkedList<T>::AppendFirst(Node<T>* node) { } template<class T> inline Node<T>* LinkedList<T>::AppendLast(T elem) { Node<T>* Temp = new Node<T>(elem); if (!this->Head) { this->Head = Temp; this->Tail = Temp; } else if (this->Head == this->Tail) { Temp->Prev = this->Tail; this->Tail->Next = Temp; this->Tail = Temp; } else { this->Tail->Next = Temp; Temp->Prev = this->Tail; this->Tail = Temp; } this->Count++; return Temp; } template<class T> inline void LinkedList<T>::AppendLast(Node<T>* node) { Node<T>* Temp = new Node<T>(elem); if (!this->Head) { this->Head = Temp; this->Tail = Temp; } else { Temp->Prev = this->Tail; this->Tail->Next = Temp; this->Tail = Temp; } this->Count++; } template<class T> inline Node<T>* LinkedList<T>::Find(T elem) { //given a value find and return a copy of the found element Node<T>* ToFind = new Node<T>(elem); Node<T>* Current = new Node<T>(); Current = this->Head; //iterate the linked list while (Current) { if (Current->Data == elem) { ToFind = Current; Current = nullptr; return ToFind; } Current = Current->Next; } return nullptr; } template<class T> inline void LinkedList<T>::Traverse() { Node<T>* Temp = new Node<T>(); Temp = this->Head; std::cout << "------START--------" << std::endl; std::cout << "Head: " << this->Head->Data << std::endl; std::cout << "Tail: " << this->Tail->Data << std::endl; std::cout << "" << std::endl; while (Temp) { std::cout << "Element: " << Temp->Data << std::endl; Temp = Temp->Next; } std::cout << "------END--------" << std::endl; std::cout << "" << std::endl; } template<class T> inline void LinkedList<T>::TraverseReverse() { Node<T>* Temp = new Node<T>(); Temp = this->Tail; std::cout << "------START--------" << std::endl; std::cout << "Head: " << this->Head->Data << std::endl; std::cout << "Tail: " << this->Tail->Data << std::endl; std::cout << "" << std::endl; while (Temp) { std::cout << "Element: " << Temp->Data << std::endl; Temp = Temp->Prev; } std::cout << "------END--------" << std::endl; std::cout << "" << std::endl; }
luca1337/LinkedLists
TreeDataStructure/LinkedListNode.h
#pragma once template <class T> struct LinkedListNode { T Data; LinkedListNode<T>* Next; LinkedListNode(T elem) { this->Data = elem; this->Next = nullptr; } LinkedListNode() { this->Data = NULL; this->Next = nullptr; } };
scatmanFATMAN/libkeystore
src/lib/entry.c
<gh_stars>0 #include <stdlib.h> #include <string.h> #include "keystore_internal.h" #include "error_internal.h" #include "util.h" #include "io.h" #include "entry.h" keystore_error_t keystore_entry_read(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_t **entry); keystore_error_t keystore_entry_write(keystore_t *keystore, keystore_entry_t *entry); static keystore_entry_note_t * keystore_entry_init_note() { keystore_entry_note_t *note; note = calloc(1, sizeof(*note)); return note; } static void keystore_entry_free_note(keystore_entry_note_t *note) { if (note != NULL) { if (note->value != NULL) { //certain things in this structure might be sensitive like: // - value util_memzero(note->value, note->value_len); free(note->value); } free(note); } } static keystore_entry_folder_t * keystore_entry_init_folder() { keystore_entry_folder_t *folder; folder = calloc(1, sizeof(*folder)); return folder; } static void keystore_entry_free_folder(keystore_entry_folder_t *folder) { keystore_entry_t *entry, *entry_del; if (folder != NULL) { entry = folder->head; while (entry != NULL) { entry_del = entry; entry = entry->next; keystore_entry_free(entry_del); } free(folder); } } keystore_entry_t * keystore_entry_init(keystore_t *keystore, keystore_entry_type_t type, const char *name) { keystore_entry_t *entry = NULL; bool success = false; size_t name_len; name_len = strlen(name); if (name_len > KEYSTORE_ENTRY_NAME_MAX) { keystore_error_set(&keystore->error, KEYSTORE_ERROR_LEN, 0, "Name is too long"); goto done; } entry = calloc(1, sizeof(*entry)); if (entry == NULL) { keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } entry->name_len = name_len; entry->name = malloc(entry->name_len + 1); if (entry->name == NULL) { keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } switch (type) { case KEYSTORE_ENTRY_TYPE_NOTE: entry->data = keystore_entry_init_note(); break; case KEYSTORE_ENTRY_TYPE_FOLDER: entry->data = keystore_entry_init_folder(); break; } if (entry->data == NULL) { keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); return NULL; } entry->type = type; strcpy(entry->name, name); entry->created = time(NULL); entry->modified = entry->created; success = true; done: if (!success) { if (entry != NULL) { keystore_entry_free(entry); entry = NULL; } } return entry; } void keystore_entry_free(keystore_entry_t *entry) { if (entry != NULL) { if (entry->name != NULL) { util_memzero(entry->name, entry->name_len); free(entry->name); } switch (entry->type) { case KEYSTORE_ENTRY_TYPE_NOTE: keystore_entry_free_note((keystore_entry_note_t *)entry->data); break; case KEYSTORE_ENTRY_TYPE_FOLDER: keystore_entry_free_folder((keystore_entry_folder_t *)entry->data); break; } util_memzero(entry, sizeof(*entry)); free(entry); } } keystore_entry_type_t keystore_entry_type(keystore_entry_t *entry) { return entry->type; } keystore_entry_t * keystore_entry_parent(keystore_entry_t *entry) { return entry->parent; } const char * keystore_entry_name(keystore_entry_t *entry) { return entry->name; } keystore_error_t keystore_entry_set_name(keystore_t *keystore, keystore_entry_t *entry, const char *name) { size_t name_len = 0; char *name_dupe; if (name != NULL) { name_len = strlen(name); } if (name_len == 0) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_EMPTY, 0, "Name cannot be empty"); } if (name_len > KEYSTORE_ENTRY_NAME_MAX) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_LEN, 0, "Name is too long"); } name_dupe = strdup(name); if (name_dupe == NULL) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } if (entry->name != NULL) { free(entry->name); } entry->name_len = name_len; entry->name = name_dupe; entry->modified = time(NULL); return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_value(keystore_t *keystore, keystore_entry_t *entry, const char **value, uint32_t *len) { keystore_entry_note_t *note; if (entry->type != KEYSTORE_ENTRY_TYPE_NOTE) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Must be a note"); } note = (keystore_entry_note_t *)entry->data; if (value != NULL) { *value = note->value; } if (len != NULL) { *len = note->value_len; } return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_set_value(keystore_t *keystore, keystore_entry_t *entry, const char *value) { return keystore_entry_set_valuen(keystore, entry, value, value == NULL ? 0 : strlen(value)); } keystore_error_t keystore_entry_set_valuen(keystore_t *keystore, keystore_entry_t *entry, const char *value, uint32_t len) { keystore_entry_note_t *note; char *tmp; if (entry->type != KEYSTORE_ENTRY_TYPE_NOTE) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Must be a note"); } note = (keystore_entry_note_t *)entry->data; if (value == NULL || len == 0) { note->value_len = 0; if (note->value != NULL) { free(note->value); note->value = NULL; } } else { //make sure we can allocate memory for this string first. if we can't, we don't want to lose the old value tmp = strdup(value); if (tmp == NULL) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } //free the old value and swap pointers if (note->value != NULL) { free(note->value); } note->value_len = len; note->value = tmp; } entry->modified = time(NULL); return keystore_error_ok(&keystore->error); } time_t keystore_entry_created(keystore_entry_t *entry) { return entry->created; } time_t keystore_entry_modified(keystore_entry_t *entry) { return entry->modified; } keystore_error_t keystore_entry_folder_size(keystore_t *keystore, keystore_entry_t *entry, unsigned int *size) { keystore_entry_folder_t *folder; if (entry->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Not a folder"); } folder = (keystore_entry_folder_t *)entry->data; *size = folder->size; return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_add_entry(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_t *entry) { keystore_entry_folder_t *folder; if (parent->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Parent is not a folder"); } folder = (keystore_entry_folder_t *)parent->data; if (folder->head == NULL) { folder->head = entry; folder->tail = entry; } else { folder->tail->next = entry; folder->tail = entry; } entry->parent = parent; ++folder->size; parent->modified = time(NULL); entry->modified = time(NULL); return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_get_entry(keystore_t *keystore, keystore_entry_t *parent, const char *name, keystore_entry_t **entry) { keystore_entry_folder_t *folder; keystore_entry_t *itr; if (parent->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Parent is not a folder"); } folder = (keystore_entry_folder_t *)parent->data; itr = folder->head; while (itr != NULL) { if (strcmp(itr->name, name) == 0) { *entry = itr; return keystore_error_ok(&keystore->error); } itr = itr->next; } return keystore_error_set(&keystore->error, KEYSTORE_ERROR_NOT_FOUND, 0, "Entry not found"); } keystore_error_t keystore_entry_get_entries(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_iterator_t **iterator) { keystore_entry_folder_t *folder; if (parent->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Parent is not a folder"); } *iterator = calloc(1, sizeof(**iterator)); if (*iterator == NULL) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } folder = (keystore_entry_folder_t *)parent->data; (*iterator)->entry_orig = folder->head; (*iterator)->entry = folder->head; (*iterator)->size = folder->size; return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_move_entry(keystore_t *keystore, keystore_entry_t *entry, keystore_entry_t *dst) { keystore_error_t error; keystore_entry_folder_t *folder; keystore_entry_t *parent, *prev; if (entry->parent == NULL) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_INVALID, 0, "Cannot move the root folder"); } if (entry->parent->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Parent is not a folder"); } if (keystore_entry_type(dst) != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Destination entry is not a folder"); } parent = entry->parent; folder = (keystore_entry_folder_t *)parent->data; error = keystore_entry_add_entry(keystore, dst, entry); if (error != KEYSTORE_ERROR_OK) { return error; } if (folder->head == entry) { folder->head = entry->next; } else { prev = folder->head; while (prev->next != entry) { prev = prev->next; } prev->next = entry->next; if (folder->tail == entry) { folder->tail = prev; } } parent->modified = time(NULL); --folder->size; return keystore_error_ok(&keystore->error); } keystore_error_t keystore_entry_delete_entry(keystore_t *keystore, keystore_entry_t *entry, int flags) { keystore_entry_folder_t *folder; keystore_entry_t *parent, *prev; if (entry->parent == NULL) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_INVALID, 0, "Cannot delete the root folder"); } if (entry->parent->type != KEYSTORE_ENTRY_TYPE_FOLDER) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Parent is not a folder"); } if (entry->type == KEYSTORE_ENTRY_TYPE_FOLDER) { folder = (keystore_entry_folder_t *)entry->data; if (folder->size > 0 && !(flags & KEYSTORE_ENTRY_DELETE_FLAG_RECURSIVE)) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_INVALID, 0, "Cannot delete non-empty folder"); } } parent = entry->parent; folder = (keystore_entry_folder_t *)parent->data; if (folder->head == entry) { folder->head = entry->next; } else { prev = folder->head; while (prev->next != entry) { prev = prev->next; } prev->next = entry->next; if (folder->tail == entry) { folder->tail = prev; } } parent->modified = time(NULL); --folder->size; keystore_entry_free(entry); return keystore_error_ok(&keystore->error); } //keystore_entry_read will free memory if this fails static keystore_error_t keystore_entry_read_note(keystore_t *keystore, keystore_entry_note_t *note) { keystore_error_t error; error = keystore_read_uint32(keystore, &note->value_len); if (error != KEYSTORE_ERROR_OK) { goto done; } note->value = malloc(note->value_len + 1); if (note->value == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } error = keystore_read_strn(keystore, note->value, note->value_len); if (error != KEYSTORE_ERROR_OK) { goto done; } done: return error; } static keystore_error_t keystore_entry_read_folder(keystore_t *keystore, keystore_entry_t *entry, keystore_entry_folder_t *folder) { keystore_entry_t *entry_item; keystore_error_t error; uint32_t i; error = keystore_read_uint32(keystore, &folder->size); if (error != KEYSTORE_ERROR_OK) { goto done; } for (i = 0; i < folder->size; i++) { error = keystore_entry_read(keystore, entry, &entry_item); if (error != KEYSTORE_ERROR_OK) { break; } //No nodes: H -> <- T //1 node: H -> O -> <- T //2 nodes: H -> O -> O -> <- T if (i == 0) { folder->head = entry_item; folder->tail = entry_item; } else { folder->tail->next = entry_item; folder->tail = entry_item; } } done: return error; } keystore_error_t keystore_entry_read(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_t **entry) { keystore_entry_t *entry_new = NULL; keystore_error_t error; uint8_t type; error = keystore_read_uint8(keystore, &type); if (error != KEYSTORE_ERROR_OK) { goto done; } switch (type) { case KEYSTORE_ENTRY_TYPE_NOTE: case KEYSTORE_ENTRY_TYPE_FOLDER: break; default: error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_TYPE, 0, "Invalid type"); break; } if (error != KEYSTORE_ERROR_OK) { goto done; } entry_new = calloc(1, sizeof(*entry_new)); if (entry_new == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } entry_new->type = type; error = keystore_read_uint16(keystore, &entry_new->name_len); if (error != KEYSTORE_ERROR_OK) { goto done; } entry_new->name = calloc(1, entry_new->name_len + 1); if (entry_new->name == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } error = keystore_read_strn(keystore, entry_new->name, entry_new->name_len); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_read_int64(keystore, &entry_new->created); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_read_int64(keystore, &entry_new->modified); if (error != KEYSTORE_ERROR_OK) { goto done; } switch (type) { case KEYSTORE_ENTRY_TYPE_NOTE: entry_new->data = keystore_entry_init_note(); if (entry_new->data == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } else { error = keystore_entry_read_note(keystore, (keystore_entry_note_t *)entry_new->data); } break; case KEYSTORE_ENTRY_TYPE_FOLDER: entry_new->data = keystore_entry_init_folder(); if (entry_new->data == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } else { error = keystore_entry_read_folder(keystore, entry_new, (keystore_entry_folder_t *)entry_new->data); } break; } if (error != KEYSTORE_ERROR_OK) { goto done; } entry_new->parent = parent; *entry = entry_new; error = keystore_error_ok(&keystore->error); done: if (error != KEYSTORE_ERROR_OK) { if (entry_new != NULL) { keystore_entry_free(entry_new); } } return error; } static keystore_error_t keystore_entry_write_note(keystore_t *keystore, keystore_entry_note_t *note) { keystore_error_t error; error = keystore_write_uint32(keystore, note->value_len); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_write_strn(keystore, note->value, note->value_len); if (error != KEYSTORE_ERROR_OK) { goto done; } done: return error; } static keystore_error_t keystore_entry_write_folder(keystore_t *keystore, keystore_entry_folder_t *folder) { keystore_entry_t *entry; keystore_error_t error; error = keystore_write_uint32(keystore, folder->size); if (error != KEYSTORE_ERROR_OK) { goto done; } entry = folder->head; while (entry != NULL) { error = keystore_entry_write(keystore, entry); if (error != KEYSTORE_ERROR_OK) { goto done; } entry = entry->next; } done: return error; } keystore_error_t keystore_entry_write(keystore_t *keystore, keystore_entry_t *entry) { keystore_error_t error; error = keystore_write_uint8(keystore, entry->type); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_write_uint16(keystore, entry->name_len); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_write_strn(keystore, entry->name, entry->name_len); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_write_int64(keystore, entry->created); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_write_int64(keystore, entry->modified); if (error != KEYSTORE_ERROR_OK) { goto done; } switch (entry->type) { case KEYSTORE_ENTRY_TYPE_NOTE: error = keystore_entry_write_note(keystore, (keystore_entry_note_t *)entry->data); break; case KEYSTORE_ENTRY_TYPE_FOLDER: error = keystore_entry_write_folder(keystore, (keystore_entry_folder_t *)entry->data); break; } done: return error; } const char * keystore_entry_type_str(keystore_entry_type_t type) { switch (type) { case KEYSTORE_ENTRY_TYPE_NOTE: return "Note"; case KEYSTORE_ENTRY_TYPE_FOLDER: return "Folder"; } return "Unknown"; }
scatmanFATMAN/libkeystore
src/common/os.c
<reponame>scatmanFATMAN/libkeystore<filename>src/common/os.c #include <stdio.h> #if defined(_WIN32) # include <Windows.h> #else #endif #include <string.h> #include "os.h" const char * os_dirname(const char *path, char *dir, size_t size) { char *ptr; snprintf(dir, size, "%s", path); if (strcmp(dir, "/") == 0) { return dir; } ptr = strrchr(dir, '/'); if (ptr == NULL) { snprintf(dir, size, "%s", "."); } else { *ptr = '\0'; } return dir; } const char * os_basename(const char *path, char *base, size_t size) { char *ptr; if (size == 0) { return path; } ptr = strrchr(path, '/'); if (ptr == NULL) { snprintf(base, size, "%s", path); } else { snprintf(base, size, "%s", ptr + 1); } return base; }
scatmanFATMAN/libkeystore
src/lib/error.h
#pragma once typedef enum { KEYSTORE_ERROR_OK, KEYSTORE_ERROR_MEM, KEYSTORE_ERROR_INVALID, KEYSTORE_ERROR_VERSION, KEYSTORE_ERROR_FILE_EXISTS, KEYSTORE_ERROR_INIT, KEYSTORE_ERROR_OPEN, KEYSTORE_ERROR_READ, KEYSTORE_ERROR_WRITE, KEYSTORE_ERROR_PW_SALT_DATA, KEYSTORE_ERROR_PW_SALT, KEYSTORE_ERROR_PW, KEYSTORE_ERROR_LEN, KEYSTORE_ERROR_EMPTY, KEYSTORE_ERROR_TYPE, KEYSTORE_ERROR_NOT_FOUND } keystore_error_t;
scatmanFATMAN/libkeystore
src/lib/entry.h
<filename>src/lib/entry.h<gh_stars>0 #pragma once #include <stdint.h> #include <time.h> #include "error.h" #include "entry_iterator.h" #define KEYSTORE_ENTRY_NAME_MAX 255 #define KEYSTORE_ENTRY_DELETE_FLAG_RECURSIVE (1 << 1) //<! Informs keystore_entry_delete_entry() to recursively delete child entries if it's a folder typedef struct keystore_t keystore_t; typedef struct keystore_entry_t keystore_entry_t; typedef struct keystore_entry_iterator_t keystore_entry_iterator_t; typedef enum { KEYSTORE_ENTRY_TYPE_NOTE, KEYSTORE_ENTRY_TYPE_FOLDER } keystore_entry_type_t; /** * Initializes a new KeyStore entry. Once created, the type of the entry cannot be changed. * * @param[in] keystore The KeyStore context. * @param[in] type The entry's type. * @param[in] name The entry's name. * @return A reference to a new entry or NULL if not enough memory was available. */ keystore_entry_t * keystore_entry_init(keystore_t *keystore, keystore_entry_type_t type, const char *name); /** * Frees a KeyStore entry. * * @param[in] entry The KeyStore entry. */ void keystore_entry_free(keystore_entry_t *entry); /** * Gets the KeyStore entry's type. * * @param[in] entry The KeyStore entry. * @return The KeyStore entry's type. */ keystore_entry_type_t keystore_entry_type(keystore_entry_t *entry); /** * * Get the Keystore entry's parent. * * @param[in] entry The KeyStore entry. * @return The KeyStore entry's parent. */ keystore_entry_t * keystore_entry_parent(keystore_entry_t *entry); /** * Gets the KeyStore entry's name. * * @param[in] entry The KeyStore entry. * @return The KeyStore entry's name. */ const char * keystore_entry_name(keystore_entry_t *entry); /** * Sets the KeyStore entry's name. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry. * @param[in] name The new name of the KeyStore entry. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_set_name(keystore_t *keystore, keystore_entry_t *entry, const char *name); /** * Gets the KeyStore entry's value. The entry must be a note type entry. This function can be used to retrieve both * the entry's value and length, or one of the two by passing NULL for the variable you don't care about. Passing NULL * for both value and len is pointless, but harmless. * When retrieving the value, take into considerination that it's a pointer to the value of the entry. If the entry's value * is set to something else or the entry is deleted, the pointer will not be valid anymore. If the value is NULL, then that * mean's the entry's value is blank. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry. * @param[out] value The KeyStore entry's value. Pass NULL if you do not care about this value. * @param[out] len The KeyStore entry's value's length. Pass NULL if you do not care about this value. * @return KEYSTORE_ERROR_OK on success, otherwise another error. If an error occurs, both value and len are not set. */ keystore_error_t keystore_entry_value(keystore_t *keystore, keystore_entry_t *entry, const char **value, uint32_t *len); /** * Sets the Keystore entry's value. This entry must be a note type entry. If value is NULL, then the KeyStore entry's * value will be cleared. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry. * @param[in] value The KeyStore entry's new value. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_set_value(keystore_t *keystore, keystore_entry_t *entry, const char *value); /** * Sets the Keystore entry's value. This entry must be a note type entry. If value is NULL or len is 0, then the KeyStore's * entry will be cleared. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry. * @param[in] value The KeyStore entry's new value. * @param[in] len The new value's length. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_set_valuen(keystore_t *keystore, keystore_entry_t *entry, const char *value, uint32_t len); /** * Gets the KeyStore entry's created timestamp. * * @param[in] entry The KeyStore entry. * @return The created timestamp of the KeyStore entry. */ time_t keystore_entry_created(keystore_entry_t *entry); /** * Gets the KeyStore entry's modified timestamp. * * @param[in] entry The KeyStore entry. * @return The modified timestamp of the KeyStore entry. */ time_t keystore_entry_modified(keystore_entry_t *entry); /** * Gets the KeyStore entry's folder size. The entry must be a KEYSTORE_ENTRY_TYPE_FOLDER type. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry to get the folder size of. * @param[out] size The memory location to store the size of the folder. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_folder_size(keystore_t *keystore, keystore_entry_t *entry, unsigned int *size); /** * Adds a KeyStore entry parent entry. The parent entry must be a KEYSTORE_ENTRY_TYPE_FOLDER type. * * @param[in] keystore The KeyStore context. * @param[in] parent The KeyStore entry to add the new entry to. * @param[in] entry The KeyStore entry to add. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_add_entry(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_t *entry); /** * Gets a KeyStore entry from the parent entry which must be a KEYSTORE_ENTRY_TYPE_FOLDER type. * * @param[in] keystore The KeyStore context. * @param[in] parent The KeyStore entry to look in. * @param[in] name The name of the KeyStore entry to look for. * @param[out] entry If found, the entry will be stored in this pointer. * @return KEYSTORE_ERROR_OK if found, otherwise another error. */ keystore_error_t keystore_entry_get_entry(keystore_t *keystore, keystore_entry_t *parent, const char *name, keystore_entry_t **entry); /** * Gets an iterator of entries for this KeyStore entry. The iterator must be free'd with * keystore_entry_iterator_free() once it's done being used. * * @param[in] keystore The KeyStore context. * @param[in] parent The KeyStore entry to look in. * @param[out] iterator The iterator of entries in the parent entry. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_get_entries(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_iterator_t **iterator); /** * Moves a KeyStore entry to a new folder. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry to move. * @param[in] dst The KeyStore entry to move to. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_entry_move_entry(keystore_t *keystore, keystore_entry_t *entry, keystore_entry_t *dst); /** * Deletes a KeyStore entry. By default, this function does not let you delete * folders that are not empty. In order to delete folders that are not empty, * use the KEYSTORE_ENTRY_DELETE_FLAG_RECURSIVE flag. * * @param[in] keystore The KeyStore context. * @param[in] entry The KeyStore entry to delete. * @param[in] flags Flags that control how to delete. * @return KEYSTORE_ERROR_OK on success, otherwise another error. * KEYSTORE_ENTRY_DELETE_FLAG_RECURSIVE */ keystore_error_t keystore_entry_delete_entry(keystore_t *keystore, keystore_entry_t *entry, int flags); /** * Reads a KeyStore entry from the KeyStore file. * * @param[in] keystore The KeyStore context. * @param[in] entry The entry to return. * @return KEYSTORE_ERROR_OK if found, otherwise another error. */ //SUGGEST REMOVING FROM PUBLIC API. FORWARD DECLARE IN keystore.c //keystore_error_t keystore_entry_read(keystore_t *keystore, keystore_entry_t **entry); /** * Writes a KeyStorey entry to the KeyStore file. * * @param[in] keystore The KeyStore context. * @param[in] entry The entry to write. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ //SUGGEST REMOVING FROM PUBLIC API. FORWARD DECLARE IN keystore.c //keystore_error_t keystore_entry_write(keystore_t *keystore, keystore_entry_t *entry); /** * Returns a string describing the entry type. * * @param[in] type The KeyStore entry type. * @return A string literal. */ const char * keystore_entry_type_str(keystore_entry_type_t type);
scatmanFATMAN/libkeystore
src/lib/crypt.c
<gh_stars>0 #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <errno.h> #include <openssl/rand.h> #include <openssl/err.h> #if defined(_WIN32) #else # include <sys/random.h> #endif #include "../crypt_blowfish-1.3/ow-crypt.h" #include "util.h" #include "crypt.h" void crypt_init() { #if OPENSSL_API_COMPAT < 0x10100000L OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); #endif } void crypt_free() { #if OPENSSL_API_COMPAT < 0x10100000L ERR_free_strings(); EVP_cleanup(); #endif } keystore_error_t crypt_bcrypt(keystore_errors_t *errors, const char *salt, const char *password, char *hash) { keystore_error_t error = KEYSTORE_ERROR_OK; char *setting = NULL, salt_in[CRYPT_BCRYPT_SALT_SIZE], *pw; void *data = NULL; int data_size = 0; //both `data` and `data_size` must be initialized to NULL and 0. crypt_ra() will re-use this structure if not NULL and possibly call realloc() on it. //for our case, we'll always input a new structure. nothing will be cached but it's just easier //get random data for the salt if not provided if (salt != NULL) { setting = malloc(CRYPT_BCRYPT_SETTING_SIZE); strcpy(setting, "$2b$12$"); memcpy(setting + 7, salt, CRYPT_BCRYPT_SALT_SIZE); } else { #if defined(_WIN32) #else if (getrandom(salt_in, sizeof(salt_in), 0) == -1) { error = keystore_error_set(errors, KEYSTORE_ERROR_PW_SALT_DATA, errno, "Failed to generate random data for salt"); goto done; } setting = crypt_gensalt_ra("$2b$", 12, salt_in, sizeof(salt_in)); if (setting == NULL) { error = keystore_error_set(errors, KEYSTORE_ERROR_PW_SALT, errno, "Failed to generate salt"); goto done; } #endif } pw = crypt_ra(password, setting, &data, &data_size); if (pw == NULL) { error = keystore_error_set(errors, KEYSTORE_ERROR_PW, errno, "Failed to generate password hash"); goto done; } strcpy(hash, pw); done: if (setting != NULL) { free(setting); } if (data != NULL) { free(data); } //we don't need to free(pw) because it's allocated as part of the opaque `data` structure return error; } keystore_error_t crypt_bcrypt_matches(keystore_errors_t *errors, const char *password, const char *hash) { char salt[CRYPT_BCRYPT_SALT_SIZE], password_hash[CRYPT_BCRYPT_SIZE + 1]; bool matches = true; keystore_error_t error; int i; memcpy(salt, hash + 7, sizeof(salt)); error = crypt_bcrypt(errors, salt, password, password_hash); if (error != KEYSTORE_ERROR_OK) { return error; } for (i = 0; i < CRYPT_BCRYPT_SIZE; i++) { if (hash[i] != password_hash[i]) { matches = false; } } if (!matches) { return keystore_error_set(errors, KEYSTORE_ERROR_INVALID, 0, "Password is invalid"); } return keystore_error_ok(errors); } keystore_error_t crypt_aes256_iv(keystore_errors_t *errors, unsigned char *iv) { if (!RAND_bytes(iv, CRYPT_AES256_IV_SIZE)) { return keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } return keystore_error_ok(errors); } keystore_error_t crypt_aes256_encrypt(keystore_errors_t *errors, const char *plain, const char *key, unsigned char *iv, unsigned char **encrypted, int *encrypted_len) { keystore_error_t error = KEYSTORE_ERROR_OK; EVP_CIPHER_CTX *ctx; int plain_len, len; //get random bytes fro the IV if (!RAND_bytes(iv, CRYPT_AES256_IV_SIZE)) { return keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } plain_len = strlen(plain); //allocate a buffer big enough to fit the cipher. that is the length of the plain text + any padding to make the size divisible by the block size *encrypted = malloc((plain_len / CRYPT_AES256_BLOCK_SIZE + 1) * CRYPT_AES256_BLOCK_SIZE); if (encrypted == NULL) { return keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { error = keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } if (!EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (unsigned char *)key, iv)) { error = keystore_error_set(errors, KEYSTORE_ERROR_INIT, 0, "Init: %s", ERR_reason_error_string(ERR_get_error())); goto done; } if (!EVP_EncryptUpdate(ctx, *encrypted, &len, (unsigned char *)plain, plain_len)) { error = keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Update: %s", ERR_reason_error_string(ERR_get_error())); goto done; } *encrypted_len = len; if (!EVP_EncryptFinal_ex(ctx, *encrypted + *encrypted_len, &len)) { error = keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Final: %s", ERR_reason_error_string(ERR_get_error())); goto done; } *encrypted_len += len; done: if (ctx != NULL) { EVP_CIPHER_CTX_free(ctx); } if (error != KEYSTORE_ERROR_OK) { free(*encrypted); return error; } return keystore_error_ok(errors); } keystore_error_t crypt_aes256_decrypt(keystore_errors_t *errors, const unsigned char *encrypted, int encrypted_len, const char *key, const unsigned char *iv, char **plain) { keystore_error_t error = KEYSTORE_ERROR_OK; EVP_CIPHER_CTX *ctx; int plain_len, len; //the plain text cannot be longer than the cipher size *plain = malloc(encrypted_len + 1); if (plain == NULL) { return keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { error = keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (unsigned char *)key, iv)) { error = keystore_error_set(errors, KEYSTORE_ERROR_INIT, 0, "Init: %s", ERR_reason_error_string(ERR_get_error())); goto done; } if (!EVP_DecryptUpdate(ctx, *(unsigned char **)plain, &len, encrypted, encrypted_len)) { error = keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Update: %s", ERR_reason_error_string(ERR_get_error())); goto done; } plain_len = len; if (!EVP_DecryptFinal_ex(ctx, *(unsigned char **)plain + len, &len)) { error = keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Final: %s", ERR_reason_error_string(ERR_get_error())); goto done; } plain_len += len; (*plain)[plain_len] = '\0'; done: if (ctx != NULL) { EVP_CIPHER_CTX_free(ctx); } if (error != KEYSTORE_ERROR_OK) { free(*plain); return error; } return keystore_error_ok(errors); } keystore_error_t crypt_aes256_file_encrypt_open(keystore_errors_t *errors, crypt_file_t *file, const char *path, const char *key) { keystore_error_t error = KEYSTORE_ERROR_OK; file->f = fopen(path, "w"); if (file->f == NULL) { return keystore_error_set(errors, KEYSTORE_ERROR_OPEN, errno, "Open: %s", strerror(errno)); } //get random bytes fro the IV if (!RAND_bytes(file->iv, CRYPT_AES256_IV_SIZE)) { error = keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } file->ctx = EVP_CIPHER_CTX_new(); if (file->ctx == NULL) { error = keystore_error_set(errors, KEYSTORE_ERROR_MEM, 0, "Out of memory"); goto done; } if (!EVP_EncryptInit_ex(file->ctx, EVP_aes_256_cbc(), NULL, (unsigned char *)key, file->iv)) { error = keystore_error_set(errors, KEYSTORE_ERROR_INIT, 0, "Init: %s", ERR_reason_error_string(ERR_get_error())); goto done; } done: if (error != KEYSTORE_ERROR_OK) { if (file->f != NULL) { fclose(file->f); } if (file->ctx != NULL) { EVP_CIPHER_CTX_free(file->ctx); } //zero out memory for the IV util_memzero(file, sizeof(*file)); return error; } return keystore_error_ok(errors); } keystore_error_t crypt_aes256_file_encrypt_write(keystore_errors_t *errors, crypt_file_t *file, const char *plain, int plain_len) { unsigned char encrypted[CRYPT_AES256_BLOCK_SIZE]; int len, plain_len_chunk; keystore_error_t error; //write in aes256 block size chunks so the file gets encrypted and written in a stream like manner so //we don't need to put the entire file into memory do { if (plain_len >= CRYPT_AES256_BLOCK_SIZE) { plain_len_chunk = CRYPT_AES256_BLOCK_SIZE; } else { plain_len_chunk = CRYPT_AES256_BLOCK_SIZE - plain_len; } plain_len -= plain_len_chunk; if (!EVP_EncryptUpdate(file->ctx, encrypted, &len, (unsigned char *)plain, plain_len_chunk)) { error = keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Update: %s", ERR_reason_error_string(ERR_get_error())); goto done; } if (fwrite(encrypted, sizeof(unsigned char), len, file->f) != len) { return keystore_error_set(errors, KEYSTORE_ERROR_WRITE, errno, "Write: %s", strerror(errno)); } } while (plain_len > 0); done: return error; } keystore_error_t crypt_aes256_file_encrypt_close(keystore_errors_t *errors, crypt_file_t *file) { unsigned char encrypted[CRYPT_AES256_BLOCK_SIZE]; int len; if (!EVP_EncryptFinal_ex(file->ctx, encrypted, &len)) { return keystore_error_set(errors, KEYSTORE_ERROR_WRITE, 0, "Final: %s", ERR_reason_error_string(ERR_get_error())); } if (len > 0) { if (fwrite(encrypted, sizeof(unsigned char), len, file->f) != len) { return keystore_error_set(errors, KEYSTORE_ERROR_WRITE, errno, "Write: %s", strerror(errno)); } } EVP_CIPHER_CTX_free(file->ctx); fclose(file->f); return keystore_error_ok(errors); }
scatmanFATMAN/libkeystore
src/lib/entry_iterator.c
#include <stdlib.h> #include "keystore_internal.h" #include "entry_iterator.h" void keystore_entry_iterator_free(keystore_entry_iterator_t *iterator) { if (iterator != NULL) { free(iterator); } } unsigned int keystore_entry_iterator_size(keystore_entry_iterator_t *iterator) { return iterator->size; } bool keystore_entry_iterator_has_next(keystore_entry_iterator_t *iterator) { return iterator->entry != NULL; } keystore_entry_t * keystore_entry_iterator_next(keystore_entry_iterator_t *iterator) { keystore_entry_t *entry; entry = iterator->entry; if (iterator->entry != NULL) { iterator->entry = iterator->entry->next; } return entry; } void keystore_entry_iterator_rewind(keystore_entry_iterator_t *iterator) { iterator->entry = iterator->entry_orig; }
scatmanFATMAN/libkeystore
src/lib/error_internal.c
<reponame>scatmanFATMAN/libkeystore #include <stdio.h> #include <stdarg.h> #include "error_internal.h" keystore_error_t keystore_error_set(keystore_errors_t *errors, keystore_error_t error, int error_sys, const char *fmt, ...) { va_list ap; errors->error = error; errors->error_sys = error_sys; va_start(ap, fmt); vsnprintf(errors->error_str, sizeof(errors->error_str), fmt, ap); va_end(ap); return error; } keystore_error_t keystore_error_ok(keystore_errors_t *errors) { errors->error = KEYSTORE_ERROR_OK; errors->error_sys = 0; errors->error_str[0] = '\0'; return KEYSTORE_ERROR_OK; }
scatmanFATMAN/libkeystore
src/common/os.h
#pragma once const char * os_dirname(const char *path, char *dir, size_t size); const char * os_basename(const char *path, char *base, size_t size);
scatmanFATMAN/libkeystore
src/lib/keystore_internal.h
#pragma once #include <stdio.h> #include <stdint.h> #include <time.h> #include "keystore.h" #include "crypt.h" #include "error_internal.h" typedef struct { char magic[4]; //!< Defines a KeyStore file. uint8_t version[3]; //!< The version of the KeyStore; 0=major, 1=minor, 2=patch unsigned char iv[CRYPT_AES256_IV_SIZE]; //!< The IV for AES256 CBC encryption of the KeyStore when saved. char password[CRYPT_BCRYPT_SIZE + 1]; //!< The bcrypt'd password to decrypt the KeyStore. } keystore_header_t; struct keystore_entry_t { keystore_entry_type_t type; uint16_t name_len; char *name; time_t created; time_t modified; void *data; struct keystore_entry_t *parent; struct keystore_entry_t *next; }; typedef struct { uint32_t value_len; char *value; } keystore_entry_note_t; typedef struct { uint32_t size; struct keystore_entry_t *head; struct keystore_entry_t *tail; } keystore_entry_folder_t; struct keystore_entry_iterator_t { keystore_entry_t *entry_orig; keystore_entry_t *entry; unsigned int size; }; struct keystore_t { FILE *f; keystore_errors_t error; keystore_header_t header; struct keystore_entry_t *root; };
scatmanFATMAN/libkeystore
src/lib/keystore.c
#include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <stdarg.h> #include <string.h> #include <errno.h> #include "error_internal.h" #include "keystore_internal.h" #include "version.h" #include "util.h" #include "fs.h" #include "io.h" #include "crypt.h" #include "keystore.h" #define KEYSTORE_FILE_PREFIX "KSSN" #define KEYSTORE_FILE_PREFIX_LEN 4 static int initialized = 0; //forward declarations for things that shouldn't be public keystore_error_t keystore_entry_read(keystore_t *keystore, keystore_entry_t *parent, keystore_entry_t **entry); keystore_error_t keystore_entry_write(keystore_t *keystore, keystore_entry_t *entry); keystore_t * keystore_init() { keystore_t *keystore; if (initialized++ == 0) { crypt_init(); } keystore = calloc(1, sizeof(*keystore)); return keystore; } void keystore_free(keystore_t *keystore) { if (--initialized == 0) { crypt_free(); //protect against people calling keystore_free() too many times if (initialized < 0) { initialized = 0; } } if (keystore != NULL) { keystore_close(keystore); free(keystore); } } //TODO: only keep ->error? static void keystore_close_no_reset(keystore_t *keystore) { if (keystore != NULL) { if (keystore->f != NULL) { fclose(keystore->f); keystore->f = NULL; } if (keystore->root != NULL) { keystore_entry_free(keystore->root); } } } keystore_error_t keystore_open(keystore_t *keystore, const char *path, const char *password) { keystore_error_t error = KEYSTORE_ERROR_OK; keystore->f = fopen(path, "rb+"); if (keystore->f == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_OPEN, errno, "%s", strerror(errno)); goto done; } //reader the header: magic error = keystore_read(keystore, (unsigned char *)keystore->header.magic, 4); if (error != KEYSTORE_ERROR_OK) { goto done; } if (strncmp(keystore->header.magic, KEYSTORE_FILE_PREFIX, KEYSTORE_FILE_PREFIX_LEN) != 0) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_INVALID, 0, "Not a keystore file"); goto done; } //read the header: version error = keystore_read(keystore, keystore->header.version, 3); if (error != KEYSTORE_ERROR_OK) { goto done; } if (keystore->header.version[0] > VERSION_MAJOR) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_VERSION, 0, "Invalid major version"); goto done; } //read the header: IV error = keystore_read(keystore, keystore->header.iv, sizeof(keystore->header.iv)); if (error != KEYSTORE_ERROR_OK) { goto done; } //read the header: password error = keystore_read(keystore, (unsigned char *)keystore->header.password, sizeof(keystore->header.password) - 1); if (error != KEYSTORE_ERROR_OK) { goto done; } keystore->header.password[sizeof(keystore->header.password) - 1] = '\0'; error = crypt_bcrypt_matches(&keystore->error, password, keystore->header.password); if (error != KEYSTORE_ERROR_OK) { goto done; } error = keystore_entry_read(keystore, NULL, &keystore->root); done: if (error != KEYSTORE_ERROR_OK) { keystore_close_no_reset(keystore); //keystore_close(keystore); } return error; } keystore_error_t keystore_close(keystore_t *keystore) { if (keystore != NULL) { keystore_close_no_reset(keystore); util_memzero(keystore, sizeof(*keystore)); } return keystore_error_ok(&keystore->error); } int keystore_version_major(keystore_t *keystore) { return keystore == NULL ? -1 : keystore->header.version[0]; } int keystore_version_minor(keystore_t *keystore) { return keystore == NULL ? -1 : keystore->header.version[1]; } int keystore_version_patch(keystore_t *keystore) { return keystore == NULL ? -1 : keystore->header.version[2]; } const char * keystore_error(keystore_t *keystore) { return keystore == NULL ? NULL : keystore->error.error_str; } keystore_entry_t * keystore_root(keystore_t *keystore) { if (keystore_is_open(keystore)) { return keystore->root; } return NULL; } bool keystore_is_open(keystore_t *keystore) { return keystore != NULL && keystore->f != NULL; } keystore_error_t keystore_create(keystore_t *keystore, const char *path, const char *password) { keystore_error_t error = KEYSTORE_ERROR_OK; if (fs_file_exists(path)) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_FILE_EXISTS, 0, "File exists"); return error; } keystore->f = fopen(path, "wb+"); if (keystore->f == NULL) { error = keystore_error_set(&keystore->error, KEYSTORE_ERROR_OPEN, errno, "%s", strerror(errno)); return error; } memcpy(keystore->header.magic, KEYSTORE_FILE_PREFIX, KEYSTORE_FILE_PREFIX_LEN); keystore->header.version[0] = VERSION_MAJOR; keystore->header.version[1] = VERSION_MINOR; keystore->header.version[2] = VERSION_PATCH; error = crypt_bcrypt(&keystore->error, NULL, password, keystore->header.password); if (error != KEYSTORE_ERROR_OK) { goto done; } keystore->root = keystore_entry_init(keystore, KEYSTORE_ENTRY_TYPE_FOLDER, "root"); keystore_save(keystore); done: keystore_close_no_reset(keystore); //keystore_close(keystore); return error; } //#error TODO: change keystore_write and keystore_read functions to take the keystore_errors struct keystore_error_t keystore_save(keystore_t *keystore) { keystore_error_t error; rewind(keystore->f); //generate an IV used to encrypt the file //everytime the file is saved, we'll generate a new IV error = crypt_aes256_iv(&keystore->error, keystore->header.iv); if (error != KEYSTORE_ERROR_OK) { return error; } error = keystore_write(keystore, (unsigned char *)keystore->header.magic, 4); if (error == KEYSTORE_ERROR_OK) { error = keystore_write(keystore, keystore->header.version, 3); } if (error == KEYSTORE_ERROR_OK) { error = keystore_write(keystore, keystore->header.iv, sizeof(keystore->header.iv)); } if (error == KEYSTORE_ERROR_OK) { error = keystore_write(keystore, (unsigned char *)keystore->header.password, sizeof(keystore->header.password) - 1); } //write the root and recursively write all entries error = keystore_entry_write(keystore, keystore->root); if (error == KEYSTORE_ERROR_OK ) { fflush(keystore->f); } return error; }
scatmanFATMAN/libkeystore
src/lib/fs.h
#pragma once #include <stdbool.h> bool fs_file_exists(const char *path);
scatmanFATMAN/libkeystore
src/client_cli/color.h
#pragma once typedef enum { COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_CYAN, COLOR_MAGENTA } color_t; void color_set(color_t color); void color_reset(); void color_printf(color_t color, const char *fmt, ...);
scatmanFATMAN/libkeystore
src/lib/keystore.h
#pragma once #include <stdbool.h> #include "error.h" #include "entry.h" #include "entry_iterator.h" #define KEYSTORE_PASSWORD_MAX 255 typedef struct keystore_t keystore_t; /** * Initializes the KeyStore context. The pointer returned is dynamically allocated and must be free'd * by calling keystore_free(). * * @return The KeyStore context or NULL if not enough memory was available. */ keystore_t * keystore_init(); /** * Frees a KeyStore context and closes the KeyStore if one is open. * * @param[in] keystore The KeyStore context. */ void keystore_free(keystore_t *keystore); /** * Opens a KeyStore. The KeyStore context must not already have an open KeyStore. * * @param[in] keystore The KeyStore context. * @param[in] path The file path of the KeyStore. * @param[in] password The password required for opening the KeyStore. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_open(keystore_t *keystore, const char *path, const char *password); /** * Closes a KeyStore that's open. * * @param[in] keystore The KeyStore context. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_close(keystore_t *keystore); /** * Gets the major version of the KeyStore. * * @param[in] keystore The KeyStore context. * @return The major version of the KeyStore or -1 if a KeyStore isn't open. */ int keystore_version_major(keystore_t *keystore); /** * Gets the minor version of the KeyStore. * * @param[in] keystore The KeyStore context. * @return The minor version of the KeyStore or -1 if a KeyStore isn't open. */ int keystore_version_minor(keystore_t *keystore); /** * Gets the patch version of the KeyStore. * * @param[in] keystore The KeyStore context. * @return The patch version of the KeyStore or -1 if a KeyStore isn't open. */ int keystore_version_patch(keystore_t *keystore); /** * Gets the currently stored error message of the KeyStore. This error message gets populated * after another API call fails. * * @param[in] keystore The KeyStore context. * @return The error message or a blank string if no error occurred. */ const char * keystore_error(keystore_t *keystore); /** * Gets the KeyStore's root entry. * * @param[in] keystore The KeyStore context. * @return The KeyStore's root entry or NULL if the KeyStore is not open. */ keystore_entry_t * keystore_root(keystore_t *keystore); /** * Determines if the KeyStore context has a KeyStore open. * * @param[in] keystore The KeyStore context. * @return true if a KeyStore is open, otherwise false. */ bool keystore_is_open(keystore_t *keystore); /** * Creates a new KeyStore. * * @param[in] keystore The KeyStore context. * @param[in] path The file path of the KeyStore. * @param[in] password The password required for opening the KeyStore. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_create(keystore_t *keystore, const char *path, const char *password); /** * Saves a KeyStore. * * @param[in] keystore The KeyStore context. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t keystore_save(keystore_t *keystore);
scatmanFATMAN/libkeystore
src/lib/fs.c
#if defined(_WIN32) # include <fileapi.h> #else # include <errno.h> # include <unistd.h> #endif #include "fs.h" bool fs_file_exists(const char *path) { #if defined(_WIN32) DWORD attr; attr = GetFileAttributes(path); return attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY); #else return access(path, F_OK) == 0; #endif }
scatmanFATMAN/libkeystore
src/lib/entry_iterator.h
#pragma once #include <stdbool.h> typedef struct keystore_entry_iterator_t keystore_entry_iterator_t; typedef struct keystore_entry_t keystore_entry_t; /** * Frees all memory associated with the iterator. * * @param[in] iterator The iterator. */ void keystore_entry_iterator_free(keystore_entry_iterator_t *iterator); /** * Gets the number of entries in the iterator. * * @param[in] iterator The iterator. */ unsigned int keystore_entry_iterator_size(keystore_entry_iterator_t *iterator); /** * Determines whether or not there are any more entries in the iterator. * * @param[in] iterator The iterator. * @return <tt>true</tt> if there are more entries, otherwise <tt>false</tt>. */ bool keystore_entry_iterator_has_next(keystore_entry_iterator_t *iterator); /** * Advances the iterator and returns the next entry. * * @param[in] iterator The iterator. * @return The next entry in the iterator or NULL if no more entries exist. */ keystore_entry_t * keystore_entry_iterator_next(keystore_entry_iterator_t *iterator); /** * Rewinds the iterator to the first entry. * * @param[in] iterator The iterator. */ void keystore_entry_iterator_rewind(keystore_entry_iterator_t *iterator);
scatmanFATMAN/libkeystore
src/lib/crypt.h
<filename>src/lib/crypt.h #pragma once #include <stdio.h> #include <openssl/evp.h> #include "error_internal.h" #define CRYPT_BCRYPT_SALT_SIZE 22 #define CRYPT_BCRYPT_SETTING_SIZE (7 + CRYPT_BCRYPT_SALT_SIZE) #define CRYPT_BCRYPT_SIZE (CRYPT_BCRYPT_SETTING_SIZE + 31) //128 bit (16 bytes) block and IV #define CRYPT_AES256_BLOCK_SIZE (128 / 8) #define CRYPT_AES256_IV_SIZE (128 / 8) typedef struct { FILE *f; EVP_CIPHER_CTX *ctx; unsigned char iv[CRYPT_AES256_IV_SIZE]; } crypt_file_t; void crypt_init(); void crypt_free(); /** * Hashes a password using the supplied salt. * * @param[out] errors The error object to write errors to. * @param[in] salt The salt for bcrypt. Must be CRYPT_BCRYPT_SALT_SIZE characters. * @param[in] password The data to hash. * @param[out] The resulting hash. Must be a buffer CRYPT_BCRYPT_SIZE + 1 big. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t crypt_bcrypt(keystore_errors_t *errors, const char *salt, const char *password, char *hash); /** * Compares a hash and a password to see if it's the correct password. Uses time-safe comparison. * * @param[out] errors The error object to write errors to. * @param[in] password The data to compare the hash to. * @param[in] hash The hash to compare against. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t crypt_bcrypt_matches(keystore_errors_t *errors, const char *password, const char *hash); /** * Generate a random IV to be used for AES256 CBC encryption. * * @param[out] errors The error object to write errors to. * @param[out] iv The buffer to store the IV in. The buffer must be CRYPT_AES256_IV_SIZE big. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t crypt_aes256_iv(keystore_errors_t *errors, unsigned char *iv); /** * Encrypts a string using AES256 CBC. A random IV is automatically generated and stored in the iv output parameter. * * @param[out] errors The error object to write errors to. * @param[in] plain The plain text to encrypt. * @param[in] key The key to use for encryption. * @param[out] iv The IV used for encryption. The buffer must be CRYPT_AES256_IV_SIZE big. * @param[out] encrypted The resulting encrypted cipher. Memory is allocated by the function and should be free'd by the caller. * @param[out] encrypted_len The length of the encrypted cipher. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t crypt_aes256_encrypt(keystore_errors_t *errors, const char *plain, const char *key, unsigned char *iv, unsigned char **encrypted, int *encrypted_len); /** * Decrypts a string using AES256 CBC. * * @param[out] errors The error object to write errors to. * @param[in] encrypted The encrypted cipher to decrypt. * @param[in] encrypted_len The encrypted cipher's length. * @param[in] key The key to use for decryption. * @param[in] iv The IV to use for decryption. * @param[out] plain The resulting decrypted plain text. Memory is allocated by the function, is NULL terminated, and should be free'd by the caller. * @return KEYSTORE_ERROR_OK on success, otherwise another error. */ keystore_error_t crypt_aes256_decrypt(keystore_errors_t *errors, const unsigned char *encrypted, int encrypted_len, const char *key, const unsigned char *iv, char **plain); keystore_error_t crypt_aes256_file_encrypt_open(keystore_errors_t *errors, crypt_file_t *file, const char *path, const char *key); keystore_error_t crypt_aes256_file_encrypt_write(keystore_errors_t *errors, crypt_file_t *file, const char *plain, int plain_len); keystore_error_t crypt_aes256_file_encrypt_close(keystore_errors_t *errors, crypt_file_t *file);
scatmanFATMAN/libkeystore
src/lib/util.h
<filename>src/lib/util.h #pragma once #include <string.h> void util_memzero(void *ptr, size_t len);
scatmanFATMAN/libkeystore
src/lib/error_internal.h
<gh_stars>0 #pragma once #include "error.h" typedef struct { keystore_error_t error; int error_sys; char error_str[512]; } keystore_errors_t; keystore_error_t keystore_error_set(keystore_errors_t *errors, keystore_error_t error, int error_sys, const char *fmt, ...); keystore_error_t keystore_error_ok(keystore_errors_t *errors);
scatmanFATMAN/libkeystore
src/lib/io.c
#include <stdio.h> #include <string.h> #include <errno.h> #include "portable_endian.h" #include "io.h" keystore_error_t keystore_read(keystore_t *keystore, unsigned char *dst, size_t count) { if (fread(dst, sizeof(unsigned char), count, keystore->f) != count) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_READ, errno, "Failed to read %zu bytes: %s", count, strerror(errno)); } return keystore_error_ok(&keystore->error); } keystore_error_t keystore_read_strn(keystore_t *keystore, char *dst, size_t len) { keystore_error_t error; error = keystore_read(keystore, (unsigned char *)dst, len); if (error == KEYSTORE_ERROR_OK) { dst[len] = '\0'; } return error; } keystore_error_t keystore_read_int64(keystore_t *keystore, int64_t *dst) { keystore_error_t error; error = keystore_read(keystore, (unsigned char *)dst, sizeof(*dst)); if (error == KEYSTORE_ERROR_OK) { *dst = be64toh(*dst); } return error; } keystore_error_t keystore_read_uint8(keystore_t *keystore, uint8_t *dst) { return keystore_read(keystore, dst, sizeof(*dst)); } keystore_error_t keystore_read_uint16(keystore_t *keystore, uint16_t *dst) { keystore_error_t error; error = keystore_read(keystore, (unsigned char *)dst, sizeof(*dst)); if (error == KEYSTORE_ERROR_OK) { *dst = be16toh(*dst); } return error; } keystore_error_t keystore_read_uint32(keystore_t *keystore, uint32_t *dst) { keystore_error_t error; error = keystore_read(keystore, (unsigned char *)dst, sizeof(*dst)); if (error == KEYSTORE_ERROR_OK) { *dst = be32toh(*dst); } return error; } keystore_error_t keystore_write(keystore_t *keystore, unsigned char *buf, size_t count) { if (fwrite(buf, sizeof(unsigned char), count, keystore->f) != count) { return keystore_error_set(&keystore->error, KEYSTORE_ERROR_WRITE, errno, "Failed to write %zu bytes: %s", count, strerror(errno)); } return keystore_error_ok(&keystore->error); } keystore_error_t keystore_write_strn(keystore_t *keystore, const char *data, size_t len) { return keystore_write(keystore, (unsigned char *)data, len); } keystore_error_t keystore_write_str(keystore_t *keystore, const char *data) { return keystore_write(keystore, (unsigned char *)data, strlen(data)); } keystore_error_t keystore_write_int64(keystore_t *keystore, int64_t data) { data = htobe64(data); return keystore_write(keystore, (unsigned char *)&data, sizeof(data)); } keystore_error_t keystore_write_uint8(keystore_t *keystore, uint8_t data) { return keystore_write(keystore, &data, sizeof(data)); } keystore_error_t keystore_write_uint16(keystore_t *keystore, uint16_t data) { data = htobe16(data); return keystore_write(keystore, (unsigned char *)&data, sizeof(data)); } keystore_error_t keystore_write_uint32(keystore_t *keystore, uint32_t data) { data = htobe32(data); return keystore_write(keystore, (unsigned char *)&data, sizeof(data)); }
scatmanFATMAN/libkeystore
src/client_cli/version.h
<filename>src/client_cli/version.h #pragma once #define VERSION_NAME "KeyStore Client" #define VERSION_MAJOR 0 #define VERSION_MINOR 2 #define VERSION_PATCH 0
scatmanFATMAN/libkeystore
src/client_cli/sep.h
<reponame>scatmanFATMAN/libkeystore #pragma once #include <stdbool.h> typedef struct { char **args; unsigned int size; unsigned int capacity; char error[256]; } sep_t; void sep_init(sep_t *sep); void sep_free(sep_t *sep); const char * sep_error(sep_t *sep); bool sep_parse(sep_t *sep, const char *str); unsigned int sep_size(sep_t *sep); const char * sep_get(sep_t *sep, unsigned int index); char * sep_dupe(sep_t *sep, unsigned int index); bool sep_equals(sep_t *sep, unsigned int index, const char *str);
scatmanFATMAN/libkeystore
src/lib/version.h
#pragma once #define VERSION_MAJOR 0 #define VERSION_MINOR 2 #define VERSION_PATCH 0
scatmanFATMAN/libkeystore
src/client_cli/color.c
<filename>src/client_cli/color.c<gh_stars>0 #include <stdio.h> #include <stdarg.h> #include "color.h" void color_set(color_t color) { int num = 37; switch (color) { case COLOR_RED: num = 91; break; case COLOR_GREEN: num = 92; break; case COLOR_BLUE: num = 94; break; case COLOR_YELLOW: num = 93; break; case COLOR_CYAN: num = 96; break; case COLOR_MAGENTA: num = 35; break; } printf("\033[%dm", num); } void color_reset() { printf("\033[%dm", 37); } void color_printf(color_t color, const char *fmt, ...) { va_list ap; color_set(color); va_start(ap, fmt); vprintf(fmt, ap); va_end(ap); color_reset(); }
scatmanFATMAN/libkeystore
src/lib/io.h
<reponame>scatmanFATMAN/libkeystore #pragma once #include <stdlib.h> #include "keystore_internal.h" #include "error_internal.h" keystore_error_t keystore_read(keystore_t *keystore, unsigned char *dst, size_t count); keystore_error_t keystore_read_strn(keystore_t *keystore, char *dst, size_t len); keystore_error_t keystore_read_int64(keystore_t *keystore, int64_t *dst); keystore_error_t keystore_read_uint8(keystore_t *keystore, uint8_t *dst); keystore_error_t keystore_read_uint16(keystore_t *keystore, uint16_t *dst); keystore_error_t keystore_read_uint32(keystore_t *keystore, uint32_t *dst); keystore_error_t keystore_write(keystore_t *keystore, unsigned char *buf, size_t count); keystore_error_t keystore_write_strn(keystore_t *keystore, const char *data, size_t len); keystore_error_t keystore_write_str(keystore_t *keystore, const char *data); keystore_error_t keystore_write_int64(keystore_t *keystore, int64_t data); keystore_error_t keystore_write_uint8(keystore_t *keystore, uint8_t data); keystore_error_t keystore_write_uint16(keystore_t *keystore, uint16_t data); keystore_error_t keystore_write_uint32(keystore_t *keystore, uint32_t data);
scatmanFATMAN/libkeystore
src/lib/util.c
#if defined(_WIN32) # include <Windows.h> #endif #include "util.h" void util_memzero(void *ptr, size_t len) { #if defined(_WIN32) SecureZeroMemory(ptr, len); #else volatile unsigned char *p; p = ptr; while (len-- > 0) { *p++ = 0; } #endif }
scatmanFATMAN/libkeystore
src/client_cli/main.c
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <signal.h> #include <keystore/keystore.h> #if defined(_WIN32) # include <Windows.h> # define PATH_MAX MAX_PATH #else # include <linux/limits.h> #endif #include "../common/os.h" #include "version.h" #include "color.h" #include "sep.h" #define FLAG_REQUIRE_NOT_OPEN (1 << 0) #define FLAG_REQUIRE_OPEN (1 << 1) typedef struct { char file[256]; keystore_entry_t *entry; int path_len; char path[PATH_MAX]; bool dirty; } state_t; typedef struct { const char *cmd; int flags; bool (*func)(keystore_t *, sep_t *, state_t *); const char *short_desc; } handler_t; typedef struct { char path[PATH_MAX]; int path_len; keystore_entry_t *entry; char error[256]; } path_info_t; static bool handle_add(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_cd(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_close(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_create(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_date(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_help(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_ls(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_mkdir(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_mv(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_open(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_quit(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_rename(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_rm(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_rmdir(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_save(keystore_t *keystore, sep_t *sep, state_t *state); static bool handle_version(keystore_t *keystore, sep_t *sep, state_t *state); static handler_t handlers[] = { {"add", FLAG_REQUIRE_OPEN, handle_add, "Adds an entry to the KeyStore."}, {"cd", FLAG_REQUIRE_OPEN, handle_cd, "Changes the current folder."}, {"close", FLAG_REQUIRE_OPEN, handle_close, "Closes a KeyStore."}, {"create", FLAG_REQUIRE_NOT_OPEN, handle_create, "Creates a KeyStore."}, {"date", 0, handle_date, "Displays the current date."}, {"help", 0, handle_help, "Displays this."}, {"ls", FLAG_REQUIRE_OPEN, handle_ls, "Displays all entries in the current folder."}, {"mkdir", FLAG_REQUIRE_OPEN, handle_mkdir, "Add a folder to the KeyStore."}, {"mv", FLAG_REQUIRE_OPEN, handle_mv, "Moves a KeyStore entry to another folder."}, {"open", FLAG_REQUIRE_NOT_OPEN, handle_open, "Opens a KeyStore."}, {"quit|exit", 0, handle_quit, "Quits the application."}, {"rename", FLAG_REQUIRE_OPEN, handle_rename, "Renames an entry."}, {"rm", FLAG_REQUIRE_OPEN, handle_rm, "Removes an entry from the current folder."}, {"rmdir", FLAG_REQUIRE_OPEN, handle_rmdir, "Removes a folder from the current folder."}, {"save", FLAG_REQUIRE_OPEN, handle_save, "Saves the KeyStore."}, {"version", 0, handle_version, "Displays the version of the KeyStore client and library if open."}, {NULL, false, NULL, NULL} }; static void handle_signal(int sig) { printf("Please use the 'quit' or 'exit' command to quit.\n"); } static bool get_path_info(keystore_t *keystore, state_t *state, const char *path, path_info_t *info) { char *path_dupe[2], *ptr, *save; bool success = true; memset(info, 0, sizeof(*info)); //0 needs to remain at the beginning so free() knows what to do //1 can be incremented path_dupe[0] = strdup(path); path_dupe[1] = path_dupe[0]; if (path_dupe[1][0] == '/') { info->entry = keystore_root(keystore); info->path_len = snprintf(info->path, sizeof(info->path), "%s", "/"); ++path_dupe[1]; } else { info->entry = state->entry; info->path_len = state->path_len; strcpy(info->path, state->path); } ptr = strtok_r(path_dupe[1], "/", &save); while (ptr != NULL) { if (strcmp(ptr, ".") != 0) { if (strcmp(ptr, "..") == 0) { if (keystore_entry_parent(info->entry) != NULL) { info->entry = keystore_entry_parent(info->entry); while (info->path_len >= 0 && info->path[info->path_len - 1] != '/') { info->path[info->path_len - 1] = '\0'; --info->path_len; } //remove the last slash if we're not root if (info->path_len > 1) { info->path[info->path_len - 1] = '\0'; --info->path_len; } } } else { if (keystore_entry_get_entry(keystore, info->entry, ptr, &info->entry) != KEYSTORE_ERROR_OK) { strcpy(info->error, keystore_error(keystore)); success = false; break; } if (strcmp(info->path, "/") == 0) { //we're in the root directory, so just replace the entire path with /<entry name> info->path_len = snprintf(info->path, sizeof(info->path), "/%s", keystore_entry_name(info->entry)); } else { //we're not in the root path, so we need to append the entry's name with a / info->path_len += snprintf(info->path + info->path_len, sizeof(info->path) - info->path_len, "/%s", keystore_entry_name(info->entry)); } } // if (keystore_entry_type(info->entry) != KEYSTORE_ENTRY_TYPE_FOLDER) { // strcpy(info->error, "Not a folder.\n"); // success = false; // break; // } } ptr = strtok_r(NULL, "/", &save); } free(path_dupe[0]); return success; } bool handle_add(keystore_t *keystore, sep_t *sep, state_t *state) { const char *name, *value = NULL; keystore_entry_t *entry; if (sep_size(sep) < 2) { printf("Usage: add <name> [value]\n"); return true; } name = sep_get(sep, 1); if (sep_size(sep) >= 3) { value = sep_get(sep, 2); } entry = keystore_entry_init(keystore, KEYSTORE_ENTRY_TYPE_NOTE, name); keystore_entry_set_value(keystore, entry, value); keystore_entry_add_entry(keystore, state->entry, entry); state->dirty = true; printf("Note added.\n"); return true; } bool handle_cd(keystore_t *keystore, sep_t *sep, state_t *state) { path_info_t info; const char *path; bool success = true; if (sep_size(sep) < 2) { printf("Usage: cd <path>\n"); return true; } path = sep_get(sep, 1); success = get_path_info(keystore, state, path, &info); if (!success) { printf("%s\n", info.error); return true; } state->entry = info.entry; state->path_len = info.path_len; strcpy(state->path, info.path); return true; } bool handle_close(keystore_t *keystore, sep_t *sep, state_t *state) { char answer[32], *ptr; int decision = -1; if (state->dirty) { while (decision == -1) { printf("The KeyStore has unsaved changes. Would you like to save before closing [yes|no|cancel]? "); fgets(answer, sizeof(answer), stdin); ptr = strchr(answer, '\n'); if (ptr != NULL) { *ptr = '\0'; } if (strcasecmp(answer, "yes") == 0) { decision = 0; } else if (strcasecmp(answer, "no") == 0) { decision = 1; } else if (strcasecmp(answer, "cancel") == 0) { decision = 2; } } if (decision == 0) { if (keystore_save(keystore) == KEYSTORE_ERROR_OK) { printf("KeyStore saved.\n"); } else { printf("%s\n", keystore_error(keystore)); return true; } } else if (decision == 2) { return true; } } keystore_close(keystore); printf("KeyStore closed.\n"); return true; } bool handle_create(keystore_t *keystore, sep_t *sep, state_t *state) { if (sep_size(sep) < 3) { printf("Usage: create <file> <password>.\n"); return true; } if (keystore_create(keystore, sep_get(sep, 1), sep_get(sep, 2)) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } printf("Keystore created.\n"); return true; } bool handle_date(keystore_t *keystore, sep_t *sep, state_t *state) { time_t now; struct tm tm; memset(&tm, 0, sizeof(tm)); now = time(NULL); localtime_r(&now, &tm); printf("%d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); return true; } bool handle_help(keystore_t *keystore, sep_t *sep, state_t *state) { int i; for (i = 0; handlers[i].func != NULL; i++) { color_printf(COLOR_GREEN, "%s", handlers[i].cmd); printf(" - %s\n", handlers[i].short_desc); } return true; } static void handle_ls_print_entry(keystore_entry_t *entry, bool l) { keystore_entry_type_t type; time_t created, modified; struct tm tm_created, tm_modified; type = keystore_entry_type(entry); printf(" "); switch (type) { case KEYSTORE_ENTRY_TYPE_NOTE: printf(" "); break; case KEYSTORE_ENTRY_TYPE_FOLDER: color_set(COLOR_BLUE); printf("f"); break; } printf(" %s\n", keystore_entry_name(entry)); color_reset(); if (l) { created = keystore_entry_created(entry); modified = keystore_entry_modified(entry); localtime_r(&created, &tm_created); localtime_r(&modified, &tm_modified); printf(" Created: %d-%02d-%02d %02d:%02d:%02d | Modified: %d-%02d-%02d %02d:%02d:%02d\n", tm_created.tm_year + 1900, tm_created.tm_mon + 1, tm_created.tm_mday, tm_created.tm_hour, tm_created.tm_min, tm_created.tm_sec, tm_modified.tm_year + 1900, tm_modified.tm_mon + 1, tm_modified.tm_mday, tm_modified.tm_hour, tm_modified.tm_min, tm_modified.tm_sec); } } bool handle_ls(keystore_t *keystore, sep_t *sep, state_t *state) { keystore_entry_iterator_t *itr; keystore_entry_t *entry; path_info_t info; const char *path; bool l = false; if (sep_size(sep) >= 3) { if (sep_equals(sep, 1, "-l")) { printf("Usage: ls -l <path>\n"); } l = true; path = sep_get(sep, 2); } else if (sep_size(sep) == 2) { if (sep_equals(sep, 1, "-l")) { l = true; path = "."; } else { path = sep_get(sep, 1); } } else { path = "."; } if (!get_path_info(keystore, state, path, &info)) { printf("%s\n", info.error); return true; } if (keystore_entry_type(info.entry) == KEYSTORE_ENTRY_TYPE_NOTE) { handle_ls_print_entry(info.entry, l); } else if (keystore_entry_type(info.entry) == KEYSTORE_ENTRY_TYPE_FOLDER) { keystore_entry_get_entries(keystore, info.entry, &itr); while (keystore_entry_iterator_has_next(itr)) { entry = keystore_entry_iterator_next(itr); handle_ls_print_entry(entry, l); } printf("%u entries.\n", keystore_entry_iterator_size(itr)); keystore_entry_iterator_free(itr); } return true; } bool handle_mkdir(keystore_t *keystore, sep_t *sep, state_t *state) { const char *path; char name[KEYSTORE_ENTRY_NAME_MAX + 1], dir[PATH_MAX]; keystore_entry_t *entry; path_info_t info; if (sep_size(sep) < 1) { printf("Usage: mkdir <path>\n"); return true; } path = sep_get(sep, 1); os_dirname(path, dir, sizeof(dir)); os_basename(path, name, sizeof(name)); if (!get_path_info(keystore, state, dir, &info)) { printf("%s\n", keystore_error(keystore)); return true; } if (keystore_entry_type(info.entry) != KEYSTORE_ENTRY_TYPE_FOLDER) { printf("Desination is not a folder.\n"); return true; } entry = keystore_entry_init(keystore, KEYSTORE_ENTRY_TYPE_FOLDER, name); if (keystore_entry_add_entry(keystore, info.entry, entry) != KEYSTORE_ERROR_OK) { printf("%s\n", info.error); return true; } state->dirty = true; printf("Folder added.\n"); return true; } bool handle_mv(keystore_t *keystore, sep_t *sep, state_t *state) { const char *path[2]; path_info_t info[2]; if (sep_size(sep) < 3) { printf("Usage: mv <path from> <path to>.\n"); return false; } path[0] = sep_get(sep, 1); path[1] = sep_get(sep, 2); if (!get_path_info(keystore, state, path[0], &info[0])) { printf("%s\n", info[0].error); return 1; } if (!get_path_info(keystore, state, path[1], &info[1])) { printf("%s\n", info[1].error); return 1; } if (keystore_entry_move_entry(keystore, info[0].entry, info[1].entry) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } state->dirty = true; printf("Entry moved.\n"); return true; } bool handle_open(keystore_t *keystore, sep_t *sep, state_t *state) { const char *path, *password; if (sep_size(sep) < 3) { printf("Usage: open <file> <password>.\n"); return true; } path = sep_get(sep, 1); password = sep_get(sep, 2); if (keystore_open(keystore, path, password) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } printf("Keystore opened.\n"); memset(state, 0, sizeof(*state)); os_basename(path, state->file, sizeof(state->file)); state->entry = keystore_root(keystore); state->path_len = snprintf(state->path, sizeof(state->path), "%s", "/"); return true; } bool handle_quit(keystore_t *keystore, sep_t *sep, state_t *state) { char answer[32], *ptr; int decision = -1; if (keystore_is_open(keystore)) { if (state->dirty) { while (decision == -1) { printf("The KeyStore has unsaved changes. Would you like to save before closing [yes|no|cancel]? "); fgets(answer, sizeof(answer), stdin); ptr = strchr(answer, '\n'); if (ptr != NULL) { *ptr = '\0'; } if (strcasecmp(answer, "yes") == 0) { decision = 0; } else if (strcasecmp(answer, "no") == 0) { decision = 1; } else if (strcasecmp(answer, "cancel") == 0) { decision = 2; } } if (decision == 0) { if (keystore_save(keystore) == KEYSTORE_ERROR_OK) { printf("KeyStore saved.\n"); } else { printf("%s\n", keystore_error(keystore)); return true; } } else if (decision == 2) { //abort the quit+save return true; } } } printf("Good bye.\n"); return false; } bool handle_rename(keystore_t *keystore, sep_t *sep, state_t *state) { const char *path, *name; path_info_t info; if (sep_size(sep) < 3) { printf("Usage: rename <path> <name>\n"); return true; } path = sep_get(sep, 1); name = sep_get(sep, 2); if (!get_path_info(keystore, state, path, &info)) { printf("%s\n", info.error); return true; } if (keystore_entry_set_name(keystore, info.entry, name) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } state->dirty = true; printf("Entry renamed.\n"); return true; } bool handle_rm(keystore_t *keystore, sep_t *sep, state_t *state) { const char *path; keystore_entry_t *entry; if (sep_size(sep) < 2) { printf("Usage: rm <path>\n"); return true; } path = sep_get(sep, 1); if (keystore_entry_get_entry(keystore, state->entry, path, &entry) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } if (keystore_entry_type(entry) == KEYSTORE_ENTRY_TYPE_FOLDER) { printf("Folders cannot be deleted with 'rm'. Use `rmdir` to delete folders.\n"); return true; } if (keystore_entry_delete_entry(keystore, entry, 0) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); } state->dirty = true; return true; } bool handle_rmdir(keystore_t *keystore, sep_t *sep, state_t *state) { char answer[32], *ptr; const char *path; unsigned int size; int decision = -1; keystore_entry_t *entry; if (sep_size(sep) < 2) { printf("Usage: rmdir <path>\n"); return true; } path = sep_get(sep, 1); if (keystore_entry_get_entry(keystore, state->entry, path, &entry) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } if (keystore_entry_type(entry) == KEYSTORE_ENTRY_TYPE_NOTE) { printf("Notes cannot be deleted with 'rmdir'. Use `rm` to delete notes.\n"); return true; } if (keystore_entry_folder_size(keystore, entry, &size) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return false; } if (size == 0) { decision = 0; } else { while (decision == -1) { printf("This folder has %u entries in it. Would you like to delete all entries in the folder too [yes|no]? ", size); fgets(answer, sizeof(answer), stdin); ptr = strchr(answer, '\n'); if (ptr != NULL) { *ptr = '\0'; } if (strcasecmp(answer, "yes") == 0) { decision = 0; } else if (strcasecmp(answer, "no") == 0) { decision = 1; } } } if (decision == 1) { return true; } if (keystore_entry_delete_entry(keystore, entry, KEYSTORE_ENTRY_DELETE_FLAG_RECURSIVE) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); } else { state->dirty = true; } return true; } bool handle_save(keystore_t *keystore, sep_t *sep, state_t *state) { if (keystore_save(keystore) != KEYSTORE_ERROR_OK) { printf("%s\n", keystore_error(keystore)); return true; } state->dirty = false; printf("Saved.\n"); return true; } bool handle_version(keystore_t *keystore, sep_t *sep, state_t *state) { printf("Client Version %d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); if (keystore_is_open(keystore)) { printf("Library Version %d.%d.%d\n", keystore_version_major(keystore), keystore_version_minor(keystore), keystore_version_patch(keystore)); } return true; } static handler_t * find_handler(keystore_t *keystore, const char *cmd) { handler_t *handler = NULL; char *cmd_dupe, *cmd_ptr, *save; bool found = false; int i; for (i = 0; !found && handlers[i].func != NULL; i++) { cmd_dupe = strdup(handlers[i].cmd); cmd_ptr = strtok_r(cmd_dupe, "|", &save); while (cmd_ptr != NULL) { if (strcmp(cmd_ptr, cmd) == 0) { found = true; if (handlers[i].flags & FLAG_REQUIRE_NOT_OPEN && keystore_is_open(keystore)) { printf("You must not have a KeyStore open.\n"); } else if (handlers[i].flags & FLAG_REQUIRE_OPEN && !keystore_is_open(keystore)) { printf("You must first open a KeyStore.\n"); } else { handler = &handlers[i]; } break; } cmd_ptr = strtok_r(NULL, "|", &save); } free(cmd_dupe); } if (!found) { printf("Command '%s' not found.\n", cmd); } return handler; } int main(int argc, char **argv) { const char *cmd; char line[2048]; bool running; sep_t sep; state_t state; handler_t *handler; keystore_t *keystore; printf("%s %d.%d.%d\n", VERSION_NAME, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); signal(SIGINT, handle_signal); keystore = keystore_init(); if (keystore == NULL) { fprintf(stderr, "Out of memory"); return 1; } printf("\nType `"); color_printf(COLOR_GREEN, "help"); printf("` for help.\n"); running = true; while (running) { printf("\n["); if (!keystore_is_open(keystore)) { color_printf(COLOR_YELLOW, "Not open"); } else { color_printf(COLOR_YELLOW, "%s", state.file); printf(": "); color_printf(COLOR_YELLOW, "%s", state.path); if (state.dirty) { color_printf(COLOR_RED, " *"); } } printf("]> "); if (fgets(line, sizeof(line), stdin) == NULL) { fprintf(stderr, "Error getting input\n"); break; } sep_init(&sep); sep_parse(&sep, line); if (sep_size(&sep) > 0) { cmd = sep_get(&sep, 0); handler = find_handler(keystore, cmd); if (handler != NULL) { running = handler->func(keystore, &sep, &state); } } sep_free(&sep); } if (keystore_is_open(keystore)) { keystore_close(keystore); } keystore_free(keystore); return 0; }
technicolor-research/faiss-quickeradc
IndexIVFVPQ.h
/** * Copyright (c) 2018-present, <NAME>, SAS. * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * Modifications related the introduction of Quicker ADC (Vectorized Product Quantization) * are licensed under the Clear BSD license found in the LICENSE file in the root directory * of this source tree. * * The rest of the source code is licensed under the BSD+Patents license found in the * LICENSE file in the root directory of this source tree */ // Copyright 2004-present Facebook. All Rights Reserved. // -*- c++ -*- #ifndef FAISS_INDEX_IVFVPQ_H #define FAISS_INDEX_IVFVPQ_H //#define PARALLEL_IVFVPQ 1 #include <vector> #include <omp.h> #include "IndexIVF.h" #include "IndexVPQ.h" #include "IndexPQ.h" // include IVFPQ.h to access stat object #include "IndexIVFPQ.h" #include <boost/align/aligned_allocator.hpp> namespace faiss { static uint64_t get_cycles () { #ifdef __x86_64__ uint32_t high, low; asm volatile("rdtsc \n\t" : "=a" (low), "=d" (high)); return ((uint64_t)high << 32) | (low); #else return 0; #endif } #define TIC t0 = get_cycles() #define TOC get_cycles () - t0 struct AbstractIndexIVFVPQ { int initial_scan_estim_param = 4; virtual ~AbstractIndexIVFVPQ() = default; }; struct IVFVPQSearchParameters: IVFSearchParameters { size_t scan_table_threshold; ///< use table computation or on-the-fly? int initial_scan_estim_param; ///< When building a top-k, how many vectors as a multiple of k should be scanned to estimate distance quantizers size_t scan_table_threshold_simd; ~IVFVPQSearchParameters () {} }; /** Inverted file with Product Quantizer encoding. Each residual * vector is encoded as a product quantizer code. */ template<class T_VPQ> struct IndexIVFVPQ: IndexIVF, AbstractIndexIVFVPQ { typedef T_VPQ VPQ_t; bool by_residual; ///< Encode residual or plain vector? int use_precomputed_table; ///< if by_residual, build precompute tables #ifdef ECLIPSE typedef VecProductQuantizer_4_AVX256<16> T_VPQ; #endif T_VPQ pq; ///< produces the codes // search-time parameters size_t scan_table_threshold=0; ///< use table computation or on-the-fly? size_t scan_table_threshold_simd=16; ///< use table computation or simd? /// if use_precompute_table /// size nlist * pq.M * pq.ksub std::vector <float> precomputed_table; typedef typename T_VPQ::group groupt; using vec_vec_group = std::vector<std::vector<groupt, boost::alignment::aligned_allocator<groupt, 64>>>; using vec_size = std::vector<size_t>; using vec_vec_ids = std::vector<std::vector<long>>; /// Inverted lists of groups of codes per partition, of total count per partition vec_vec_group group_codes; vec_size count_codes; // Note that std::vector < std::vector<uint8_t> > codes; is left unused (empty lists) in our implementation due to different memory layout. IndexIVFVPQ (Index * quantizer, size_t d, size_t nlist) : IndexIVF (quantizer, d, nlist, 0, METRIC_L2), pq (d) //group_codes(), //count_codes() { code_size = 0; invlists->code_size = 0; is_trained = false; by_residual = true; use_precomputed_table = 0; //scan_table_threshold_simd = 16; Must be initialized somewhere else (for deserialization) //scan_table_threshold = 0; group_codes.resize (nlist); count_codes.resize (nlist); maintain_direct_map=false; // Force direct map to false this->initial_scan_estim_param=4; // Default value, overwritten by auto-tune } void add_with_ids_internal (idx_t n, const float * x, const long *xids) { FAISS_THROW_IF_NOT (is_trained); double t0 = getmillisecs (); const long * idx; ScopeDeleter<long> del_idx; long * idx0 = new long [n]; del_idx.set (idx0); quantizer->assign (n, x, idx0); idx = idx0; double t1 = getmillisecs (); std::vector<groupt, boost::alignment::aligned_allocator<groupt, 64>> xcodes; std::vector<float> residuals; xcodes.resize(pq.nb_groups(n)); const float * to_encode; if (by_residual) { residuals.resize(n*d); for (size_t i = 0; i < n; i++) { if (idx[i] < 0) memset (residuals.data() + i * d, 0, sizeof(*residuals.data()) * d); else quantizer->compute_residual(x + i * d, residuals.data() + i * d, idx[i]); } to_encode = residuals.data(); } else { to_encode = x; } pq.encode_multiple(to_encode, xcodes.data(),0,n); double t2 = getmillisecs (); size_t n_ignore = 0; for (size_t i = 0; i < n; i++) { idx_t key = idx[i]; if (key < 0) { n_ignore ++; continue; } idx_t id = xids ? xids[i] : ntotal + i; size_t offset = invlists->add_entry (key, id, NULL /* CODE IS STORED IN GROUP_CODES NOT IN INVLISTS */); pq.append_codes(group_codes[key],&count_codes[key],xcodes.data(),i,1); if (maintain_direct_map){ direct_map.push_back (key << 32 | offset); } } double t3 = getmillisecs (); if(verbose) { char comment[100] = {0}; if (n_ignore > 0) snprintf (comment, 100, "(%ld vectors ignored)", n_ignore); printf(" add_core times: %.3f %.3f %.3f %s\n", t1 - t0, t2 - t1, t3 - t2, comment); } ntotal += n; } void add_with_ids(idx_t n, const float *x, const long * xids= nullptr) { idx_t bs = 262144; if (n > bs) { for (idx_t i0 = 0; i0 < n; i0 += bs) { idx_t i1 = std::min(i0 + bs, n); if (verbose) { printf("IndexIVFPQ::add_core_o: adding %ld:%ld / %ld\n", i0, i1, n); } add_with_ids_internal(i1 - i0, x + i0 * d, xids ? xids + i0 : nullptr); } return; } } /// trains the product quantizer void train_residual(idx_t n, const float* x) override { const float * x_in = x; x = fvecs_maybe_subsample ( d, (size_t*)&n, pq.cp.max_points_per_centroid * pq.ksub_total/pq.M, x, verbose, pq.cp.seed); ScopeDeleter<float> del_x (x_in == x ? nullptr : x); const float *trainset; ScopeDeleter<float> del_residuals; if (by_residual) { if(verbose) printf("computing residuals\n"); idx_t * assign = new idx_t [n]; // assignement to coarse centroids ScopeDeleter<idx_t> del (assign); quantizer->assign (n, x, assign); float *residuals = new float [n * d]; del_residuals.set (residuals); for (idx_t i = 0; i < n; i++) quantizer->compute_residual (x + i * d, residuals+i*d, assign[i]); trainset = residuals; } else { trainset = x; } if (verbose) printf ("training %zdx%zd product quantizer on %ld vectors in %dD\n", pq.M, pq.ksub_total, n, d); pq.verbose = verbose; pq.train (n, trainset); if (by_residual) { precompute_table (); } } void reconstruct_from_offset (long list_no, long offset, float* recons) const override { const groupt * code = group_codes[list_no].data(); if (by_residual) { std::vector<float> centroid(d); quantizer->reconstruct (list_no, centroid.data()); pq.decode (code, recons,offset); for (int i = 0; i < d; ++i) { recons[i] += centroid[i]; } } else { pq.decode (code, recons,offset); } } void merge_from (IndexIVF &other, idx_t add_id) override { FAISS_THROW_MSG("Not implemented"); } /** Precomputed tables for residuals * * During IVFPQ search with by_residual, we compute * * d = || x - y_C - y_R ||^2 * * where x is the query vector, y_C the coarse centroid, y_R the * refined PQ centroid. The expression can be decomposed as: * * d = || x - y_C ||^2 + || y_R ||^2 + 2 * (y_C|y_R) - 2 * (x|y_R) * --------------- --------------------------- ------- * term 1 term 2 term 3 * * When using multiprobe, we use the following decomposition: * - term 1 is the distance to the coarse centroid, that is computed * during the 1st stage search. * - term 2 can be precomputed, as it does not involve x. However, * because of the PQ, it needs nlist * M * ksub storage. This is why * use_precomputed_table is off by default * - term 3 is the classical non-residual distance table. * * Since y_R defined by a product quantizer, it is split across * subvectors and stored separately for each subvector. If the coarse * quantizer is a MultiIndexQuantizer then the table can be stored * more compactly. * * At search time, the tables for term 2 and term 3 are added up. This * is faster when the length of the lists is > ksub * M. */ void precompute_table () { //FIXME update precompute if (use_precomputed_table == 0) { // then choose the type of table if (quantizer->metric_type == METRIC_INNER_PRODUCT) { fprintf(stderr, "IndexIVFPQ::precompute_table: WARN precomputed " "tables not needed for inner product quantizers\n"); return; } const MultiIndexQuantizer *miq = dynamic_cast<const MultiIndexQuantizer *> (quantizer); if (miq && pq.M % miq->pq.M == 0) use_precomputed_table = 2; else use_precomputed_table = 1; } // otherwise assume user has set appropriate flag on input if (verbose) { printf ("precomputing IVFPQ tables type %d\n", use_precomputed_table); } // squared norms of the PQ centroids std::vector<float> r_norms (pq.ksub_total, NAN); for (int m = 0; m < pq.M; m++) for (int j = 0; j < pq.ksub[m]; j++) r_norms [pq.ksub_offset[m] + j] = fvec_norm_L2sqr (pq.get_centroids (m, j), pq.dsub[m]); if (use_precomputed_table == 1) { precomputed_table.resize (nlist * pq.ksub_total); std::vector<float> centroid (d); for (size_t i = 0; i < nlist; i++) { quantizer->reconstruct (i, centroid.data()); float *tab = &precomputed_table[i * pq.ksub_total]; pq.compute_inner_prod_table (centroid.data(), tab); fvec_madd (pq.ksub_total, r_norms.data(), 2.0, tab, tab); } } else if (use_precomputed_table == 2) { const MultiIndexQuantizer *miq = dynamic_cast<const MultiIndexQuantizer *> (quantizer); FAISS_THROW_IF_NOT (miq); const ProductQuantizer &cpq = miq->pq; FAISS_THROW_IF_NOT (pq.M % cpq.M == 0); FAISS_THROW_IF_NOT (pq.ksub_total % cpq.M == 0); precomputed_table.resize(cpq.ksub * pq.ksub_total); // reorder PQ centroid table std::vector<float> centroids (d * cpq.ksub, NAN); for (int m = 0; m < cpq.M; m++) { for (size_t i = 0; i < cpq.ksub; i++) { memcpy (centroids.data() + i * d + m * cpq.dsub, cpq.get_centroids (m, i), sizeof (*centroids.data()) * cpq.dsub); } } pq.compute_inner_prod_tables (cpq.ksub, centroids.data (), precomputed_table.data ()); for (size_t i = 0; i < cpq.ksub; i++) { float *tab = &precomputed_table[i * pq.ksub_total]; fvec_madd (pq.ksub_total, r_norms.data(), 2.0, tab, tab); } } } IndexIVFVPQ () { // initialize some runtime values use_precomputed_table = 0; scan_table_threshold = 0; by_residual=0; } /** QueryTables manages the various ways of searching an * IndexIVFPQ. The code contains a lot of branches, depending on: * - metric_type: are we computing L2 or Inner product similarity? * - by_residual: do we encode raw vectors or residuals? * - use_precomputed_table: are x_R|x_C tables precomputed? */ /***************************************************** * Scaning the codes. * The scanning functions call their favorite precompute_* * function to precompute the tables they need. *****************************************************/ template <typename IDType> struct QueryTables { /***************************************************** * General data from the IVFPQ *****************************************************/ const IndexIVFVPQ<T_VPQ> & ivfpq; // copied from IndexIVFPQ for easier access int d; const T_VPQ & pq; MetricType metric_type; bool by_residual; int use_precomputed_table; // pre-allocated data buffers float * sim_table, * sim_table_2; float * residual_vec, *decoded_vec; // single data buffer std::vector<float> mem; // for table pointers std::vector<const float *> sim_table_ptrs; const groupt * __restrict list_codes; const IDType * list_ids; size_t list_size; size_t already_scanned; size_t codes_needed_to_build_quantizer; size_t n_simd_eval; explicit QueryTables (const IndexIVFVPQ<T_VPQ> & ivfpq, int k, const IVFSearchParameters *params): ivfpq(ivfpq), d(ivfpq.d), pq (ivfpq.pq), metric_type (ivfpq.metric_type), by_residual (ivfpq.by_residual), use_precomputed_table (ivfpq.use_precomputed_table), list_codes(NULL), list_ids(NULL), list_size(0), already_scanned(0), codes_needed_to_build_quantizer(ivfpq.initial_scan_estim_param*k) { mem.resize (pq.ksub_total * 2 + d *2); sim_table = mem.data(); sim_table_2 = sim_table + pq.ksub_total; residual_vec = sim_table_2 + pq.ksub_total; decoded_vec = residual_vec + d; init_list_cycles = 0; sim_table_ptrs.resize(pq.M); if (auto ivfvpq_params = dynamic_cast<const IVFVPQSearchParameters *>(params)) { codes_needed_to_build_quantizer = k*ivfvpq_params->initial_scan_estim_param; } key=0; coarse_dis=0.0; qi=NULL; n_simd_eval = 0; } /***************************************************** * What we do when query is known *****************************************************/ // field specific to query const float * qi; // query-specific intialization void init_query (const float * qi) { this->qi = qi; this->already_scanned=0; if (metric_type == METRIC_INNER_PRODUCT) init_query_IP (); else init_query_L2 (); } void init_query_IP () { // precompute some tables specific to the query qi pq.compute_inner_prod_table (qi, sim_table); // we compute negated inner products for use with the maxheap for (int i = 0; i < pq.ksub_total; i++) { sim_table[i] = - sim_table[i]; } } void init_query_L2 () { if (!by_residual) { pq.compute_distance_table (qi, sim_table); } else if (use_precomputed_table) { pq.compute_inner_prod_table (qi, sim_table_2); } } /***************************************************** * When inverted list is known: prepare computations *****************************************************/ // fields specific to list Index::idx_t key; float coarse_dis; //std::vector<uint8_t> q_code; uint64_t init_list_cycles; /// once we know the query and the centroid, we can prepare the /// sim_table that will be used for accumulation /// and dis0, the initial value float precompute_list_tables () { float dis0 = 0; uint64_t t0; TIC; if (by_residual) { if (metric_type == METRIC_INNER_PRODUCT) dis0 = precompute_list_tables_IP (); else dis0 = precompute_list_tables_L2 (); } init_list_cycles += TOC; return dis0; } float precompute_list_table_pointers () { float dis0 = 0; uint64_t t0; TIC; if (by_residual) { if (metric_type == METRIC_INNER_PRODUCT) FAISS_THROW_MSG ("not implemented"); else dis0 = precompute_list_table_pointers_L2 (); } init_list_cycles += TOC; return dis0; } /***************************************************** * compute tables for inner prod *****************************************************/ float precompute_list_tables_IP () { // prepare the sim_table that will be used for accumulation // and dis0, the initial value ivfpq.quantizer->reconstruct (key, decoded_vec); // decoded_vec = centroid float dis0 = -fvec_inner_product (qi, decoded_vec, d); return dis0; } /***************************************************** * compute tables for L2 distance *****************************************************/ float precompute_list_tables_L2 () { float dis0 = 0; if (use_precomputed_table == 0) { ivfpq.quantizer->compute_residual (qi, residual_vec, key); pq.compute_distance_table (residual_vec, sim_table); } else if (use_precomputed_table == 1) { dis0 = coarse_dis; fvec_madd (pq.ksub_total, &ivfpq.precomputed_table [key * pq.ksub_total], -2.0, sim_table_2, sim_table); } else if (use_precomputed_table == 2) { dis0 = coarse_dis; const MultiIndexQuantizer *miq = dynamic_cast<const MultiIndexQuantizer *> (ivfpq.quantizer); FAISS_THROW_IF_NOT (miq); const ProductQuantizer &cpq = miq->pq; // int Mf = pq.M / cpq.M; const float *qtab = sim_table_2; // query-specific table float *ltab = sim_table; // (output) list-specific table long k = key; for (int cm = 0; cm < cpq.M; cm++) { // compute PQ index int ki = k & ((uint64_t(1) << cpq.nbits) - 1); k >>= cpq.nbits; // get corresponding table const float *pc = &ivfpq.precomputed_table[ki*pq.ksub_total + cm*pq.ksub_total/cpq.M]; // [(ki * pq.M + cm * Mf) * pq.ksub]; // sum up with query-specific table fvec_madd (pq.ksub_total / cpq.M, pc, -2.0, qtab, ltab); ltab += pq.ksub_total / cpq.M; qtab += pq.ksub_total / cpq.M; } } return dis0; } float precompute_list_table_pointers_L2 () { float dis0 = 0; if (use_precomputed_table == 1) { dis0 = coarse_dis; const float * s = &ivfpq.precomputed_table [key * pq.ksub_total]; for (int m = 0; m < pq.M; m++) { sim_table_ptrs [m] = &s[pq.ksub_offset[m]]; } } else if (use_precomputed_table == 2) { dis0 = coarse_dis; const MultiIndexQuantizer *miq = dynamic_cast<const MultiIndexQuantizer *> (ivfpq.quantizer); FAISS_THROW_IF_NOT (miq); const ProductQuantizer &cpq = miq->pq; int Mf = pq.M / cpq.M; long k = key; int m0 = 0; for (int cm = 0; cm < cpq.M; cm++) { int ki = k & ((uint64_t(1) << cpq.nbits) - 1); k >>= cpq.nbits; const float *pc = &ivfpq.precomputed_table[ki*pq.ksub_total + cm*pq.ksub_total/cpq.M]; //const float *pc = &ivfpq.precomputed_table // [(ki * pq.M + cm * Mf) * pq.ksub]; for (int m = m0; m < m0 + Mf; m++) { sim_table_ptrs [m] = &pc[pq.ksub_offset[m]]; } m0 += Mf; } } else { FAISS_THROW_MSG ("need precomputed tables"); } return dis0; } /// list_specific intialization void init_list (Index::idx_t key, float coarse_dis, size_t list_size_in, const IDType *list_ids_in, const groupt *list_codes_in) { this->key = key; this->coarse_dis = coarse_dis; list_size = list_size_in; list_codes = list_codes_in; list_ids = list_ids_in; } /***************************************************** * Scaning the codes: simple PQ scan. *****************************************************/ /// version of the scan where we use precomputed tables void scan_list_with_table ( size_t k, float * heap_sim, long * heap_ids, bool store_pairs) { float dis0 = precompute_list_tables (); pq.lookup_and_update_heap(list_size, 0, list_codes,sim_table,k, heap_sim, heap_ids, dis0, key, list_ids, store_pairs); already_scanned += list_size; } void scan_list_with_table_simd ( size_t k, float * heap_sim, long * heap_ids, bool store_pairs) { float dis0 = precompute_list_tables (); size_t scanned_with_nonquantized_distances = 0; if(already_scanned < codes_needed_to_build_quantizer){ scanned_with_nonquantized_distances = std::min(codes_needed_to_build_quantizer-already_scanned,list_size); pq.lookup_and_update_heap(scanned_with_nonquantized_distances, 0, list_codes,sim_table,k, heap_sim, heap_ids, dis0, key, list_ids, store_pairs); already_scanned += scanned_with_nonquantized_distances; } if(already_scanned >= codes_needed_to_build_quantizer){ std::vector<typename T_VPQ::QuantTableLane,boost::alignment::aligned_allocator<typename T_VPQ::QuantTableLane, 64>> mm_dis_tables; mm_dis_tables.resize(pq.dt_lanes_total); typename T_VPQ::VPQQuant* qmax = pq.quantize_tables(sim_table, mm_dis_tables.data(), maxheap_worst_value(k, heap_sim)); /* Test if the quantizer was built, i.e. if we need to scan the inverted list */ if(qmax != nullptr){ pq.lookup_and_update_heap_simd(list_size-scanned_with_nonquantized_distances, scanned_with_nonquantized_distances, list_codes, sim_table, mm_dis_tables.data(), qmax, k, heap_sim, heap_ids, dis0, key, list_ids, store_pairs); delete qmax; } n_simd_eval += list_size-scanned_with_nonquantized_distances; already_scanned += list_size-scanned_with_nonquantized_distances; }else{ //printf("already scanned: %d\n",(int)already_scanned); //printf("needed: %d\n",(int)codes_needed_to_build_quantizer); //printf("list_size: %d\n",(int)list_size); //printf("scanned_nq: %d\n",(int)scanned_with_nonquantized_distances); //printf("Number of entries remaining %d\n",(int)(list_size-scanned_with_nonquantized_distances)); FAISS_THROW_IF_NOT_MSG(0 == list_size-scanned_with_nonquantized_distances,"Remaining to scan"); } } /// tables are not precomputed, but pointers are provided to the /// relevant X_c|x_r tables void scan_list_with_pointer ( size_t k, float * heap_sim, long * heap_ids, bool store_pairs) { float dis0 = precompute_list_table_pointers (); for (size_t j = 0; j < list_size; j++) { float dis = dis0; for (size_t m = 0; m < pq.M; m++) { unsigned ci = pq.get_code_component(list_codes, j, m); dis += sim_table_ptrs [m][ci] - 2 * sim_table_2[pq.ksub_offset[m]+ci]; } if (dis < heap_sim[0]) { maxheap_pop (k, heap_sim, heap_ids); long id = store_pairs ? (key << 32 | j) : list_ids[j]; maxheap_push (k, heap_sim, heap_ids, dis, id); } } already_scanned += list_size; } /// nothing is precomputed: access residuals on-the-fly void scan_on_the_fly_dist ( size_t k, float * heap_sim, long * heap_ids, bool store_pairs) { if (by_residual && use_precomputed_table) { scan_list_with_pointer (k, heap_sim, heap_ids, store_pairs); return; } const float *dvec; float dis0 = 0; if (by_residual) { if (metric_type == METRIC_INNER_PRODUCT) { ivfpq.quantizer->reconstruct (key, residual_vec); dis0 = fvec_inner_product (residual_vec, qi, d); } else { ivfpq.quantizer->compute_residual (qi, residual_vec, key); } dvec = residual_vec; } else { dvec = qi; dis0 = 0; } for (size_t j = 0; j < list_size; j++) { pq.decode (list_codes, decoded_vec, j); float dis; if (metric_type == METRIC_INNER_PRODUCT) { dis = -dis0 - fvec_inner_product (decoded_vec, qi, d); } else { dis = fvec_L2sqr (decoded_vec, dvec, d); } if (dis < heap_sim[0]) { maxheap_pop (k, heap_sim, heap_ids); long id = store_pairs ? (key << 32 | j) : list_ids[j]; maxheap_push (k, heap_sim, heap_ids, dis, id); } } already_scanned += list_size; } }; void search_preassigned (idx_t nx, const float *qx, idx_t k, const idx_t *keys, const float *coarse_dis, float *distances, idx_t *labels, bool store_pairs, const IVFSearchParameters *params=nullptr ) const override { float_maxheap_array_t res = { size_t(nx), size_t(k), labels, distances }; #pragma omp parallel { QueryTables<long> qt (*this,k,params); size_t stats_nlist = 0; size_t stats_ncode = 0; uint64_t init_query_cycles = 0; uint64_t scan_cycles = 0; uint64_t heap_cycles = 0; long local_nprobe = params ? params->nprobe : nprobe; long local_max_codes = params ? params->max_codes : max_codes; //uint64_t local_scan_table_threshold_simd= params ? params-> scan_table_threshold_simd : scan_table_threshold_simd; //uint64_t local_scan_table_threshold= params ? params-> scan_table_threshold : scan_table_threshold; #pragma omp for for (size_t i = 0; i < nx; i++) { const float *qi = qx + i * d; const long * keysi = keys + i * nprobe; const float *coarse_dis_i = coarse_dis + i * nprobe; float * heap_sim = res.get_val (i); long * heap_ids = res.get_ids (i); uint64_t t0; TIC; maxheap_heapify (k, heap_sim, heap_ids); heap_cycles += TOC; TIC; qt.init_query (qi); init_query_cycles += TOC; size_t nscan = 0; for (size_t ik = 0; ik < local_nprobe; ik++) { long key = keysi[ik]; /* select the list */ if (key < 0) { // not enough centroids for multiprobe continue; } FAISS_THROW_IF_NOT_FMT ( key < (long) nlist, "Invalid key=%ld at ik=%ld nlist=%ld\n", key, ik, nlist); size_t list_size = invlists->list_size (key); stats_nlist ++; nscan += list_size; if (list_size == 0) continue; qt.init_list (key, coarse_dis_i[ik], list_size, InvertedLists::ScopedIds (invlists, key).get(), group_codes[key].data()); TIC; if(list_size > scan_table_threshold_simd) { qt.scan_list_with_table_simd (k, heap_sim, heap_ids, store_pairs); }else if(list_size > scan_table_threshold) { qt.scan_list_with_table (k, heap_sim, heap_ids, store_pairs); } else { qt.scan_on_the_fly_dist (k, heap_sim, heap_ids, store_pairs); } scan_cycles += TOC; if (local_max_codes && nscan >= local_max_codes) break; } stats_ncode += nscan; TIC; maxheap_reorder (k, heap_sim, heap_ids); if (metric_type == METRIC_INNER_PRODUCT) { for (size_t j = 0; j < k; j++) heap_sim[j] = -heap_sim[j]; } heap_cycles += TOC; } #pragma omp critical { indexIVFPQ_stats.nlist += stats_nlist; indexIVFPQ_stats.ncode += stats_ncode; indexIVFPQ_stats.n_hamming_pass += qt.n_simd_eval; indexIVFPQ_stats.init_query_cycles += init_query_cycles; indexIVFPQ_stats.init_list_cycles += qt.init_list_cycles; indexIVFPQ_stats.scan_cycles += scan_cycles - qt.init_list_cycles; indexIVFPQ_stats.heap_cycles += heap_cycles; } } indexIVFPQ_stats.nq += nx; } }; // Reuse statistic structure from IVFPQ template <class T> inline std::string fourcc_vpq(const IndexIVFVPQ<T>* n){return "J"+cc_vpq((T*)NULL);} } // namespace faiss #endif
technicolor-research/faiss-quickeradc
VPQ_Impl.h
<filename>VPQ_Impl.h /** * Copyright (c) 2018 - Present – <NAME>, SAS * All rights reserved. * * This source code is licensed under the Clear BSD license found in the * LICENSE file in the root directory of this source tree. */ // -*- c++ -*- #ifndef FAISS_VPQI_H #define FAISS_VPQI_H #ifndef SWIG #include "VecProductQuantizer.h" #include "IndexVPQ.h" #include "IndexIVFVPQ.h" #endif namespace faiss { // First character: precision (1: 32 bits, 2: 64 bits, 4: 128 bits, ...) // Second character is the implementation: // q : quantized scalar, // t: quantized scalar (table based) // s: non-quantized scalar // v: vectorized // V,T,Q,S: cross-lane (2 lanes) implem (pshufb over AVX256) // W: cross-lane (4 lanes) implem (pshufb over AVX512) // // Saved indexes can be converted by editing the file with an hexeditor // and changing the letter as long as the layout and precision remain the same // // Third character is the layout: // 4,4 => 4 // 6,6,4 => 6, // 6,5,5 => a // 5,5,5 => b // 8,8 => c // 8 => 8 #ifdef SWIG #define DVP_TAIL(b,...) \ __VA_ARGS__ #define DVP_HEAD_CONCAT(a,b,...) \ a##b #define DVP(a,...) \ %template(DVP_HEAD_CONCAT(IndexVPQ_,__VA_ARGS__)) faiss::IndexVPQ<faiss::DVP_TAIL(__VA_ARGS__)>; \ #else #define DVP(fn, a,...) \ typedef __VA_ARGS__ VPQ_##a; \ typedef IndexVPQ<__VA_ARGS__> IndexVPQ_##a ; \ typedef IndexIVFVPQ<__VA_ARGS__> IndexIVFVPQ_##a ; \ inline std::string cc_vpq(const VPQ_##a * n){ return #a;} \ inline std::string factName(const VPQ_##a * n){ return #fn;} #endif // 64bit quantizers DVP(VPQ_12x6.6.4_NV , 2q6 , VecProductQuantizer_NoVec<12,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x6.5.5_NV , 2qa , VecProductQuantizer_NoVec<12,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x5.5.5_NV , 2qb , VecProductQuantizer_NoVec<12,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_16x4.4_NV , 2q4 , VecProductQuantizer_NoVec<16,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_16x4.4_NV_AVX2 , 2Q4 , VecProductQuantizer_NoVec<16,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_12x6.6.4_NVT , 2t6 , VecProductQuantizer_NoVecTable<12,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x6.5.5_NVT , 2ta , VecProductQuantizer_NoVecTable<12,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x5.5.5_NVT , 2tb , VecProductQuantizer_NoVecTable<12,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_16x4.4_NVT , 2t4 , VecProductQuantizer_NoVecTable<16,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_16x4.4_NVT_AVX2 , 2T4 , VecProductQuantizer_NoVecTable<16,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_12x6.6.4_NQ , 2s6 , VecProductQuantizer_NoVecNoQuant<12,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x6.6.4_NQ , 2sa , VecProductQuantizer_NoVecNoQuant<12,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_12x6.6.4_NQ , 2sb , VecProductQuantizer_NoVecNoQuant<12,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_16x4.4_NQ , 2s4 , VecProductQuantizer_NoVecNoQuant<16,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_16x4.4_NQ_AVX2 , 2S4 , VecProductQuantizer_NoVecNoQuant<16,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_12x6.6.4_AVX512, 2v6 , VecProductQuantizer_XYZ_AVX512_unsigned<12,6,6,4>) DVP(VPQ_12x6.5.5_AVX512, 2va , VecProductQuantizer_XYZ_AVX512_unsigned<12,6,5,5>) DVP(VPQ_12x5.5.5_AVX512, 2vb , VecProductQuantizer_XYZ_AVX512_unsigned<12,5,5,5>) DVP(VPQ_16x4.4_SSE , 2v4 , VecProductQuantizer_4_SSE128_unsigned<16>) DVP(VPQ_16x4.4_AVX512 , 2W4 , VecProductQuantizer_4_AVX512_unsigned<16>) DVP(VPQ_16x4.4_AVX2 , 2V4 , VecProductQuantizer_4_AVX256_unsigned<16>) DVP(VPQ_8x8.8_AVX512, 2vc, VecProductQuantizer_88_AVX512_unsigned<8>) DVP(VPQ_16x8_AVX512, 2v8, VecProductQuantizer_8_AVX512_unsigned<8>) // 128bit quantizers DVP(VPQ_24x6.6.4_NV , 4q6 , VecProductQuantizer_NoVec<24,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x6.5.5_NV , 4qa , VecProductQuantizer_NoVec<24,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x5.5.5_NV , 4qb , VecProductQuantizer_NoVec<24,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_32x4.4_NV , 4q4 , VecProductQuantizer_NoVec<32,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_32x4.4_NV_AVX2 , 4Q4 , VecProductQuantizer_NoVec<32,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_24x6.6.4_NVT , 4t6 , VecProductQuantizer_NoVecTable<24,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x6.5.5_NVT , 4ta , VecProductQuantizer_NoVecTable<24,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x5.5.5_NVT , 4tb , VecProductQuantizer_NoVecTable<24,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_32x4.4_NVT , 4t4 , VecProductQuantizer_NoVecTable<32,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_32x4.4_NVT_AVX2 , 4T4 , VecProductQuantizer_NoVecTable<32,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_24x6.6.4_NQ , 4s6 , VecProductQuantizer_NoVecNoQuant<24,3,6,6,4,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x6.6.4_NQ , 4sa , VecProductQuantizer_NoVecNoQuant<24,3,6,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_24x6.6.4_NQ , 4sb , VecProductQuantizer_NoVecNoQuant<24,3,5,5,5,0,uint16_t,__m512i,__m512i>) DVP(VPQ_32x4.4_NQ , 4s4 , VecProductQuantizer_NoVecNoQuant<32,2,4,4,0,0,uint8_t,__m128i,__m128i>) DVP(VPQ_32x4.4_NQ_AVX2 , 4S4 , VecProductQuantizer_NoVecNoQuant<32,2,4,4,0,0,uint8_t,__m128i,__m256i>) DVP(VPQ_24x6.6.4_AVX512, 4v6 , VecProductQuantizer_XYZ_AVX512_unsigned<24,6,6,4>) DVP(VPQ_24x6.5.5_AVX512, 4va , VecProductQuantizer_XYZ_AVX512_unsigned<24,6,5,5>) DVP(VPQ_24x5.5.5_AVX512, 4vb , VecProductQuantizer_XYZ_AVX512_unsigned<24,5,5,5>) DVP(VPQ_32x4.4_SSE , 4v4 , VecProductQuantizer_4_SSE128_unsigned<32>) DVP(VPQ_32x4.4_AVX512 , 4W4 , VecProductQuantizer_4_AVX512_unsigned<32>) DVP(VPQ_32x4.4_AVX2 , 4V4 , VecProductQuantizer_4_AVX256_unsigned<32>) DVP(VPQ_16x8.8_AVX512, 4vc, VecProductQuantizer_88_AVX512_unsigned<16>) DVP(VPQ_16x8_AVX512, 4v8, VecProductQuantizer_8_AVX512_unsigned<16>) // Regular DVP(VPQ_8x8_NQ , 2s8 , VecProductQuantizer_NoVecNoQuant<8,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x8_NQ , 1s8 , VecProductQuantizer_NoVecNoQuant<4,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x8_NQ , 4s8 , VecProductQuantizer_NoVecNoQuant<16,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_8x8_NV , 2q8 , VecProductQuantizer_NoVec<8,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x8_NV , 1q8 , VecProductQuantizer_NoVec<4,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x8_NV , 4q8 , VecProductQuantizer_NoVec<16,1,8,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_8x7_NQ , 2s7 , VecProductQuantizer_NoVecNoQuant<8,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x7_NQ , 1s7 , VecProductQuantizer_NoVecNoQuant<4,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x7_NQ , 4s7 , VecProductQuantizer_NoVecNoQuant<16,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_8x7_NV , 2q7 , VecProductQuantizer_NoVec<8,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x7_NV , 1q7 , VecProductQuantizer_NoVec<4,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x7_NV , 4q7 , VecProductQuantizer_NoVec<16,1,7,0,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_8x7.1_NQ , 2sd , VecProductQuantizer_NoVecNoQuant<8,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x7.1_NQ , 1sd , VecProductQuantizer_NoVecNoQuant<4,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x7.1_NQ , 4sd , VecProductQuantizer_NoVecNoQuant<16,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_8x7.1_NV , 2qd , VecProductQuantizer_NoVec<8,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_4x7.1_NV , 1qd , VecProductQuantizer_NoVec<4,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) DVP(VPQ_16x7.1_NV , 4qd , VecProductQuantizer_NoVec<16,2,7,1,0,0,uint8_t,uint8_t,uint8_t>) // Additional DVP(VPQ_30x6.6.4_AVX512, 5v6 , VecProductQuantizer_XYZ_AVX512_unsigned<30,6,6,4>) DVP(VPQ_30x6.5.5_AVX512, 5va , VecProductQuantizer_XYZ_AVX512_unsigned<30,6,5,5>) DVP(VPQ_30x5.5.5_AVX512, 5vb , VecProductQuantizer_XYZ_AVX512_unsigned<30,5,5,5>) } // namespace faiss #define EXPAND_VPQTEST(F) \ F(VPQ_2q6) || \ F(VPQ_2qa) || \ F(VPQ_2qb) || \ F(VPQ_2q4) || \ F(VPQ_2Q4) || \ F(VPQ_2s6) || \ F(VPQ_2sa) || \ F(VPQ_2sb) || \ F(VPQ_2s4) || \ F(VPQ_2S4) || \ F(VPQ_2t6) || \ F(VPQ_2ta) || \ F(VPQ_2tb) || \ F(VPQ_2t4) || \ F(VPQ_2T4) || \ F(VPQ_2v6) || \ F(VPQ_2va) || \ F(VPQ_2vb) || \ F(VPQ_2v4) || \ F(VPQ_2V4) || \ F(VPQ_2W4) || \ F(VPQ_4q6) || \ F(VPQ_4qa) || \ F(VPQ_4qb) || \ F(VPQ_4q4) || \ F(VPQ_4Q4) || \ F(VPQ_4s6) || \ F(VPQ_4sa) || \ F(VPQ_4sb) || \ F(VPQ_4s4) || \ F(VPQ_4S4) || \ F(VPQ_4t6) || \ F(VPQ_4ta) || \ F(VPQ_4tb) || \ F(VPQ_4t4) || \ F(VPQ_4T4) || \ F(VPQ_4v6) || \ F(VPQ_4va) || \ F(VPQ_4vb) || \ F(VPQ_4v4) || \ F(VPQ_4V4) || \ F(VPQ_4W4) || \ F(VPQ_5v6) || \ F(VPQ_5va) || \ F(VPQ_5vb) || \ F(VPQ_2s8) || \ F(VPQ_2s7) || \ F(VPQ_1s7) || \ F(VPQ_4s7) || \ F(VPQ_2q7) || \ F(VPQ_1q7) || \ F(VPQ_4q7) || \ F(VPQ_2vc) || \ F(VPQ_4vc) || \ F(VPQ_2v8) || \ F(VPQ_4v8) #endif
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/huffman_coding_priv_config.h
<reponame>MilosSubotic/huffman_coding /** * @license MIT * @brief Private calculated configurations for Huffman coding. */ #ifndef HUFFMAN_CODING_PRIV_CONFIG_H #define HUFFMAN_CODING_PRIV_CONFIG_H /////////////////////////////////////////////////////////////////////////////// #include <cmath> #include "huffman_coding_config.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { // Calculated by huffman_tree_depth.jl script. const int max_dep = 11; // Max depth. // Calculated. const int sym_num = 1 << sym_width; // Max number of frequencies. const int freq_width = block_len_log2 + 1; const int node_width = freq_width; const int num_freq = block_len; const int dep_width = ceil(log2(max_dep + 1)); const int len_width = dep_width; const int len_freq_width = freq_width; const int len_freq_num = max_dep + 1; const int code_width = max_dep; const int max_code_len = code_width; const int enc_bit_acc_width = 2*enc_chunk_width-1; const int enc_bit_acc_size_width = ceil(log2(enc_bit_acc_width + 1)); const int enc_bit_acc_extract_width = ceil(log2(enc_chunk_width + 1)); } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_PRIV_CONFIG_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/include/huffman_coding_public_types.h
<gh_stars>1-10 /** * @license MIT * @brief Public type definitions for Huffman coding. */ #ifndef HUFFMAN_CODING_PUBLIC_TYPES_H #define HUFFMAN_CODING_PUBLIC_TYPES_H /////////////////////////////////////////////////////////////////////////////// #include <stdint.h> #include <systemc.h> #include "huffman_coding_config.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { typedef sc_uint<sym_width> sym_t; typedef sc_uint<enc_chunk_width> enc_chunk_t; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_PUBLIC_TYPES_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/hd_sym_unpacker.h
/** * @license MIT * @brief */ #ifndef HD_SYM_UNPACKER_H #define HD_SYM_UNPACKER_H /////////////////////////////////////////////////////////////////////////////// #include "axis_channel.h" #include "bit_extract_channel.h" #include "huffman_coding_interfaces.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { SC_MODULE(hd_sym_unpacker) { public: bit_extract_client_port<enc_bit_acc_t, enc_bit_acc_size_t, enc_bit_acc_extract_t> bit_stream; axis_in<lens_freq_t> in_lens_freq; axis_out<codes_len_and_code_table_t> out_codes_len_and_code_table; SC_CTOR(hd_sym_unpacker) { SC_THREAD(unpack); } private: void unpack(); }; } /////////////////////////////////////////////////////////////////////////////// #endif // HD_SYM_UNPACKER_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules/source/src/huffman_coding_interfaces.h
/** * @license MIT * @brief Huffman coding interfaces between modules. */ #ifndef HUFFMAN_CODING_INTERFACES_H #define HUFFMAN_CODING_INTERFACES_H /////////////////////////////////////////////////////////////////////////////// #include "huffman_coding_structs.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_INTERFACES_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/hd_lens_freq_unpacker.h
/** * @license MIT * @brief */ #ifndef HD_LENS_FREQ_UNPACKER_H #define HD_LENS_FREQ_UNPACKER_H /////////////////////////////////////////////////////////////////////////////// #include "axis_channel.h" #include "bit_extract_channel.h" #include "huffman_coding_interfaces.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { SC_MODULE(hd_lens_freq_unpacker) { public: bit_extract_client_port<enc_bit_acc_t, enc_bit_acc_size_t, enc_bit_acc_extract_t> bit_stream; axis_out<lens_freq_t> out_lens_freq; SC_CTOR(hd_lens_freq_unpacker) { SC_THREAD(unpack); } private: void unpack(); }; } /////////////////////////////////////////////////////////////////////////////// #endif // HD_LENS_FREQ_UNPACKER_H
MilosSubotic/huffman_coding
Algo/huffman_coding/include/huffman_coding_public_types.h
<reponame>MilosSubotic/huffman_coding /** * @license MIT * @brief Public type definitions for Huffman coding. */ #ifndef HUFFMAN_CODING_PUBLIC_TYPES_H #define HUFFMAN_CODING_PUBLIC_TYPES_H /////////////////////////////////////////////////////////////////////////////// #include <stdint.h> #include "huffman_coding_config.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { typedef uint32_t sym_t; // sym_width typedef uint32_t enc_chunk_t; // enc_chunk_width } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_PUBLIC_TYPES_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules/source/include/huffman_coding_print.h
/** * @license MIT * @brief Print stuff for types and structs. */ #ifndef HUFFMAN_CODING_PRINT_H #define HUFFMAN_CODING_PRINT_H /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include <vector> #include <deque> #include <systemc.h> /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { class binary_ostream { public: explicit binary_ostream(std::ostream& os) : _os(os) {} template<typename T> binary_ostream& operator<<(const T& x) { _os << x; return *this; } binary_ostream& operator<<(std::ostream& (*pf)(std::ostream&)) { pf(_os); return *this; } template<int W> binary_ostream& operator<<(const sc_uint<W>& x) { this->print(x); return *this; } private: std::ostream& _os; void print(const sc_uint_base&); }; template<typename T> binary_ostream& operator<<(binary_ostream& bos, std::vector<T> v) { auto iter = v.begin(); auto last = v.end() - 1; for(; iter != last; iter++){ bos << *iter << std::endl; } bos << *last; return bos; } template<typename T> binary_ostream& operator<<(binary_ostream& bos, std::deque<T> v) { auto iter = v.begin(); auto last = v.end() - 1; for(; iter != last; iter++){ bos << *iter << std::endl; } bos << *last; return bos; } extern binary_ostream bcout; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_STRUCTS_H
MilosSubotic/huffman_coding
Algo/huffman_coding/include/huffman_coding.h
<gh_stars>1-10 /** * @license MIT * @brief Huffman coding function interfaces. */ #ifndef HUFFMAN_CODING_H #define HUFFMAN_CODING_H /////////////////////////////////////////////////////////////////////////////// #include <vector> #include "huffman_coding_public_types.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { void huffman_encode( const std::vector<sym_t>& in_data, std::vector<enc_chunk_t>& out_enc_data ); void huffman_decode( const std::vector<enc_chunk_t>& in_enc_data, std::vector<sym_t>& out_data ); } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/include/huffman_decoder.h
<gh_stars>1-10 /** * @license MIT * @brief */ #ifndef HUFFMAN_DECODER_H #define HUFFMAN_DECODER_H /////////////////////////////////////////////////////////////////////////////// #include <vector> #include "axis_channel.h" #include "huffman_coding_public_types.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { SC_MODULE(huffman_decoder) { public: axis_in<enc_chunk_t> in_enc_data; axis_out<sym_t> out_data; SC_CTOR(huffman_decoder) { SC_THREAD(decode); init(); } private: void init(); void decode(); }; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_DECODER_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/bit_extract_channel.h
<gh_stars>1-10 /** * @license MIT * @brief SystemC channel for extracting bits from type. */ #ifndef BIT_EXTRACT_CHANNEL_H #define BIT_EXTRACT_CHANNEL_H /////////////////////////////////////////////////////////////////////////////// #include <systemc.h> #include <cassert> /////////////////////////////////////////////////////////////////////////////// // BA is short for Bit Accumulator type. // BAS is short for Bit Accumulator Size type. // BAE is short for Bit Accumulator Extract type. enum bit_extract_operation_t { EXTRACT_BITS, NEED_MORE_BITS, DONE }; template<typename BA, typename BAS, typename BAE> class bit_extract_server_if : virtual public sc_interface { public: virtual void open_connection(const BA& acc, const BAS& size) = 0; virtual bit_extract_operation_t wait_operation() = 0; virtual BAE get_extract() const = 0; }; template<typename BA, typename BAS, typename BAE> class bit_extract_client_if : virtual public sc_interface { public: virtual void connect() = 0; virtual const BA& get_acc() const = 0; virtual const BAS& get_size() const = 0; virtual void extract_bits(BAE bits_to_extract) = 0; virtual void need_more_bits() = 0; virtual void done() = 0; }; template<typename BA, typename BAS, typename BAE> class bit_extract_channel : public sc_channel, public bit_extract_server_if<BA, BAS, BAE>, public bit_extract_client_if<BA, BAS, BAE> { public: bit_extract_channel(sc_module_name name) : sc_channel(name), connection_opened(false), acc(nullptr), size(nullptr), op(DONE) { } virtual void open_connection(const BA& acc, const BAS& size) { this->acc = &acc; this->size = &size; connection_opened = true; connection_event.notify(); } virtual bit_extract_operation_t wait_operation() { server_done_op.notify(); wait(client_set_op); return op; } virtual BAE get_extract() const { return extract; } virtual void connect() { if(!connection_opened){ wait(connection_event); } } virtual const BA& get_acc() const { return *acc; } virtual const BAS& get_size() const { return *size; } virtual void extract_bits(BAE bits_to_extract) { extract = bits_to_extract; op = bit_extract_operation_t::EXTRACT_BITS; client_set_op.notify(); wait(server_done_op); } virtual void need_more_bits() { op = bit_extract_operation_t::NEED_MORE_BITS; client_set_op.notify(); wait(server_done_op); } virtual void done() { connection_opened = false; op = bit_extract_operation_t::DONE; client_set_op.notify(); } protected: bool connection_opened; sc_event connection_event; const BA* acc; const BAS* size; BAE extract; bit_extract_operation_t op; sc_event client_set_op, server_done_op; }; template<typename BA, typename BAS, typename BAE> class bit_extract_server_port : public sc_port<bit_extract_server_if<BA, BAS, BAE>> { }; template<typename BA, typename BAS, typename BAE> class bit_extract_client_port : public sc_port<bit_extract_client_if<BA, BAS, BAE>> { }; /////////////////////////////////////////////////////////////////////////////// #endif // BIT_EXTRACT_CHANNEL_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/huffman_coding_priv_types.h
<reponame>MilosSubotic/huffman_coding /** * @license MIT * @brief Private type definitions for Huffman coding. */ #ifndef HUFFMAN_CODING_PRIV_TYPES_H #define HUFFMAN_CODING_PRIV_TYPES_H /////////////////////////////////////////////////////////////////////////////// #include <stdint.h> #include <systemc.h> #include "huffman_coding_public_types.h" #include "huffman_coding_priv_config.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { typedef sc_uint<freq_width> freq_t; typedef sc_uint<freq_width> node_t; typedef sc_uint<dep_width> dep_t; typedef sc_uint<len_width> len_t; typedef sc_uint<len_freq_width> len_freq_t; typedef sc_uint<code_width> code_t; typedef sc_uint<enc_bit_acc_width> enc_bit_acc_t; typedef sc_uint<enc_bit_acc_size_width> enc_bit_acc_size_t; typedef sc_uint<enc_bit_acc_extract_width> enc_bit_acc_extract_t; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_PRIV_TYPES_H
MilosSubotic/huffman_coding
Algo/other/huffman_codec/huffman_codec.h
/* * @license MIT * @brief Huffman codec, encoder and decoder. */ #ifdef __cplusplus extern "C" { #endif ////////////////////////////////////////////////////////////////////////////// #include <stdint.h> ////////////////////////////////////////////////////////////////////////////// int huffman_encode( const uint8_t* data, size_t data_len, uint8_t* compressed, size_t compressed_max_len ); int huffman_decode( const uint8_t* compressed, size_t compressed_len, uint8_t* data, size_t data_max_len ); ////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules/source/src/huffman_coding_structs.h
/** * @license MIT * @brief Huffman coding structs. */ #ifndef HUFFMAN_CODING_STRUCTS_H #define HUFFMAN_CODING_STRUCTS_H /////////////////////////////////////////////////////////////////////////////// #include <vector> #include "huffman_coding_priv_types.h" #include "huffman_coding_print.h" /////////////////////////////////////////////////////////////////////////////// #define DECLARE_BINARY_OSTREAM_OPERATOR(T) \ binary_ostream& operator<<(binary_ostream& bos, const T& x) /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { // node_width ones. const node_t null_node = (1 << (node_width))-1; class sym_and_freq { public: sym_t sym; freq_t freq; }; DECLARE_BINARY_OSTREAM_OPERATOR(sym_and_freq); class node_and_freq { public: node_t node; freq_t freq; // Null object. node_and_freq() : node(null_node), freq(null_node) {} node_and_freq(node_t node, freq_t freq) : node(node), freq(freq) {} node_and_freq(const sym_and_freq& s) : node(s.sym), freq(s.freq) {} bool is_null() const { return freq == null_node; } }; DECLARE_BINARY_OSTREAM_OPERATOR(node_and_freq); class node_and_dep { public: node_t node; dep_t dep; }; DECLARE_BINARY_OSTREAM_OPERATOR(node_and_dep); class sym_and_len{ public: sym_t sym; len_t len; }; DECLARE_BINARY_OSTREAM_OPERATOR(sym_and_len); } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_STRUCTS_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules/source/include/axis_channel.h
<reponame>MilosSubotic/huffman_coding /** * @license MIT * @brief SystemC channel for AXI4-Stream. */ #ifndef AXIS_CHANNEL_H #define AXIS_CHANNEL_H /////////////////////////////////////////////////////////////////////////////// #include <systemc.h> #include <cassert> /////////////////////////////////////////////////////////////////////////////// // DI is short for Data Interface template<typename DI> class axis_write_if : virtual public sc_interface { public: virtual void write(const DI& data, bool last = false) = 0; }; template<typename DI> class axis_read_if : virtual public sc_interface { public: virtual void read(DI& data, bool& last) = 0; }; template<typename DI> class axis_channel : public sc_channel, public axis_write_if<DI>, public axis_read_if<DI> { public: axis_channel(sc_module_name name) : sc_channel(name), have_data(false) { } virtual void write(const DI& data, bool last = false) { if(have_data){ wait(read_event); } this->data = data; this->last = last; have_data = true; write_event.notify(); } virtual void read(DI& data, bool& last) { if(!have_data){ wait(write_event); } data = this->data; last = this->last; have_data = false; read_event.notify(); } protected: DI data; bool last; bool have_data; sc_event write_event, read_event; }; template<typename DI> class axis_out : public sc_port<axis_write_if<DI>> { }; template<typename DI> class axis_in : public sc_port<axis_read_if<DI>> { }; /////////////////////////////////////////////////////////////////////////////// #endif // AXIS_CHANNEL_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/axis_bit_extract_server.h
<reponame>MilosSubotic/huffman_coding /** * @license MIT * @brief SystemC channel for extracting bits from type. */ #ifndef AXIS_BIT_EXTRACT_SERVER_H #define AXIS_BIT_EXTRACT_SERVER_H /////////////////////////////////////////////////////////////////////////////// #include <vector> #include <sstream> #include "axis_channel.h" #include "bit_extract_channel.h" /////////////////////////////////////////////////////////////////////////////// // C is short for Chunk type. // BA is short for Bit Accumulator type. // BAS is short for Bit Accumulator Size type. // BAE is short for Bit Accumulator Extract type. template<typename C, typename BA, typename BAS, typename BAE> SC_MODULE(axis_bit_extract_server) { public: SC_CTOR(axis_bit_extract_server) { chunk_stream = nullptr; SC_THREAD(serve); } void set_axis_chunk_in_if(axis_in<C>& in_chunk_if){ chunk_stream = &in_chunk_if; } private: using channel_t = bit_extract_channel<BA, BAS, BAE>; public: using client_if_t = bit_extract_client_if<BA, BAS, BAE>; client_if_t* get_new_client_if() { // Make name for bit extract channel. int idx = servers_port.size(); std::ostringstream oss; oss << basename() << "__bit_extract_channel__"<< idx; auto ch = new channel_t(oss.str().c_str()); channels.push_back(ch); auto sp = new server_port_t(); sp->operator()(*ch); servers_port.push_back(sp); return ch; } private: axis_in<C>* chunk_stream; using server_port_t = bit_extract_server_port<BA, BAS, BAE>; std::vector<channel_t*> channels; std::vector<server_port_t*> servers_port; void serve() { while(true){ for(server_port_t* server : servers_port){ BA acc; BAS acc_size; (*server)->open_connection(acc, acc_size); C chunk; bool last_chunk = false; assert(!last_chunk); (*chunk_stream)->read(chunk, last_chunk); acc = chunk; acc_size = chunk.length(); BAE extract; while(true){ switch((*server)->wait_operation()){ case EXTRACT_BITS: extract = (*server)->get_extract(); assert(extract <= acc_size); acc_size -= extract; acc >>= extract; break; case NEED_MORE_BITS: assert(!last_chunk); (*chunk_stream)->read(chunk, last_chunk); acc |= BA(chunk) << acc_size; acc_size += chunk.length(); break; case DONE: goto client_done; } } client_done: ; } } } }; /////////////////////////////////////////////////////////////////////////////// #endif // AXIS_BIT_EXTRACT_SERVER_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/src/huffman_coding_interfaces.h
/** * @license MIT * @brief Huffman coding interfaces between modules. */ #ifndef HUFFMAN_CODING_INTERFACES_H #define HUFFMAN_CODING_INTERFACES_H /////////////////////////////////////////////////////////////////////////////// #include "huffman_coding_structs.h" #include <array> /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { typedef std::array<len_freq_t, len_freq_num> lens_freq_t; typedef std::array<len_t, sym_num> codes_len_t; typedef std::array<code_t, sym_num> code_table_t; struct codes_len_and_code_table_t { codes_len_t codes_len; code_table_t code_table; }; DECLARE_BINARY_OSTREAM_OPERATOR(codes_len_and_code_table_t); } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_INTERFACES_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/include/huffman_coding.h
/** * @license MIT * @brief Huffman coding modules. */ #ifndef HUFFMAN_CODING_H #define HUFFMAN_CODING_H /////////////////////////////////////////////////////////////////////////////// #include "huffman_encoder.h" #include "huffman_decoder.h" /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/include/huffman_coding_print.h
<filename>Model/huffman_coding_untimed_modules_2/source/include/huffman_coding_print.h /** * @license MIT * @brief Print stuff for types and structs. */ #ifndef HUFFMAN_CODING_PRINT_H #define HUFFMAN_CODING_PRINT_H /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <iomanip> #include <vector> #include <deque> #include <array> #include <systemc.h> /////////////////////////////////////////////////////////////////////////////// #define DEBUG(var) \ do{ \ huffman_coding::debug_log << #var << " = " << var << std::endl; \ }while(0) #define TRACE() \ do{ \ huffman_coding::debug_log << __FUNCTION__ << ":" \ << __LINE__ << std::endl; \ }while(0) /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { class binary_ostream { public: explicit binary_ostream(std::ostream& os) : _os(os) {} template<typename T> binary_ostream& operator<<(const T& x) { _os << x; return *this; } binary_ostream& operator<<(std::ostream& (*pf)(std::ostream&)) { pf(_os); return *this; } template<int W> binary_ostream& operator<<(const sc_uint<W>& x) { this->print(x); return *this; } private: std::ostream& _os; void print(const sc_uint_base&); }; template<typename T> binary_ostream& operator<<(binary_ostream& bos, std::vector<T> v) { auto iter = v.begin(); auto last = v.end() - 1; for(; iter != last; iter++){ bos << *iter << std::endl; } bos << *last; return bos; } template<typename T> binary_ostream& operator<<(binary_ostream& bos, std::deque<T> d) { auto iter = d.begin(); auto last = d.end() - 1; for(; iter != last; iter++){ bos << *iter << std::endl; } bos << *last; return bos; } template<typename T, std::size_t N> binary_ostream& operator<<(binary_ostream& bos, std::array<T, N> a) { auto iter = a.begin(); auto last = a.end() - 1; for(; iter != last; iter++){ bos << *iter << std::endl; } bos << *last; return bos; } extern binary_ostream algo_log; extern binary_ostream debug_log; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_STRUCTS_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules/source/include/huffman_encoder.h
<filename>Model/huffman_coding_untimed_modules/source/include/huffman_encoder.h /** * @license MIT * @brief */ #ifndef HUFFMAN_ENCODER_H #define HUFFMAN_ENCODER_H /////////////////////////////////////////////////////////////////////////////// #include "axis_channel.h" #include "huffman_coding_public_types.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { class huffman_encoder : sc_module { public: axis_in<sym_t> in_data; axis_out<enc_chunk_t> out_enc_data; SC_CTOR(huffman_encoder) { SC_THREAD(encode); } private: void encode(); }; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_ENCODER_H
MilosSubotic/huffman_coding
Model/huffman_coding_untimed_modules_2/source/include/huffman_coding_config.h
/** * @license MIT * @brief Configuration file for Huffman coding. */ #ifndef HUFFMAN_CODING_CONFIG_H #define HUFFMAN_CODING_CONFIG_H /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { // User defined. const int sym_width = 8; const int block_len_log2 = 8; const int enc_chunk_width = 32; // Calculated. const int block_len = 1 << block_len_log2; } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_CONFIG_H
MilosSubotic/huffman_coding
Algo/huffman_coding/src/huffman_coding_priv_types.h
/** * @license MIT * @brief Private type definitions for Huffman coding. */ #ifndef HUFFMAN_CODING_PRIV_TYPES_H #define HUFFMAN_CODING_PRIV_TYPES_H /////////////////////////////////////////////////////////////////////////////// #include <stdint.h> #include "huffman_coding_public_types.h" #include "huffman_coding_priv_config.h" /////////////////////////////////////////////////////////////////////////////// namespace huffman_coding { typedef uint32_t freq_t; // freq_width typedef uint32_t node_t; // node_width typedef uint32_t dep_t; // dep_width typedef uint32_t len_t; // len_width typedef uint32_t len_freq_t; // len_freq_width typedef uint32_t code_t; // code_width } /////////////////////////////////////////////////////////////////////////////// #endif // HUFFMAN_CODING_PRIV_TYPES_H
mincrmatt12/MSign
esp/main/grabber/transit/gtfs.cfg.h
<gh_stars>1-10 #include "../../config.h" #include "./common.cfg.h" namespace transit::gtfs { //!cfg: holds .gtfs.feed.host, default "_webapps.regionofwaterloo.ca" extern const char * feed_host; //!cfg: holds .gtfs.feed.url, default "/api/grt-routes/api/tripupdates" extern const char * feed_url; //!cfg: holds .gtfs.alt_feed.host, default nullptr extern const char * alt_feed_host; //!cfg: holds .gtfs.alt_feed.url, default nullptr extern const char * alt_feed_url; //!cfg: receives .gtfs.entries[$n].name void update_ttc_entry_name(size_t n, const char * value); struct GtfsEntry { //!cfg: holds .route const char * route_id; //!cfg: holds .stop const char * stop_id; //!cfg: holds .route_alt const char * route_id_alt{}; //!cfg: holds .stop_alt const char * stop_id_alt{}; //!cfg: holds .use_alt_feed bool use_alt_feed = false; //!cfg: holds .dircode[0] TransitDirectionCode dir_a = NA; //!cfg: holds .dircode[1] TransitDirectionCode dir_b = NA; //!cfg: holds .distance uint8_t distance_minutes = 5; operator bool() const {return route_id && stop_id;} bool has_alt() const {return route_id_alt && stop_id_alt;} }; //!cfg: holds .gtfs.entries extern config::lazy_t<GtfsEntry> entries[5]; }
mincrmatt12/MSign
stm/src/matrix.h
<reponame>mincrmatt12/MSign #ifndef MATRIX_H #define MATRIX_H #include "crash/main.h" #include "gpio.h" #include <stdint.h> #include <string.h> #include "stm32f2xx.h" #include "stm32f2xx_ll_tim.h" #include "stm32f2xx_ll_bus.h" #include "stm32f2xx_ll_gpio.h" #include "stm32f2xx_ll_dma.h" #include "pins.h" #include <FreeRTOS.h> #include <task.h> #include "color.h" namespace led { template<uint16_t Width> struct BasicFrameBufferStorage { static const uint_fast16_t EffectiveWidth = Width; inline static color_t & _at(color_t * data, uint16_t x, uint16_t y) { return data[x + y*Width]; } inline static const color_t & _at(const color_t * data, uint16_t x, uint16_t y) { return data[x + y*Width]; } }; template<uint16_t Width, uint16_t Height, typename Storage=BasicFrameBufferStorage<Width>> struct FrameBuffer { FrameBuffer() { memset(data, 0x0, sizeof(data)); } void clear() { memset(data, 0x0, sizeof(data)); } void prepare_stream(uint16_t i, uint8_t pos) { switch (pos) { case 0: prepare_stream_bf<0>(i); return; case 1: prepare_stream_bf<1>(i); return; case 2: prepare_stream_bf<2>(i); return; case 3: prepare_stream_bf<3>(i); return; case 4: prepare_stream_bf<4>(i); return; case 5: prepare_stream_bf<5>(i); return; case 6: prepare_stream_bf<6>(i); return; case 7: prepare_stream_bf<7>(i); return; case 8: prepare_stream_bf<8>(i); return; case 9: prepare_stream_bf<9>(i); return; case 10: prepare_stream_bf<10>(i); return; case 11: prepare_stream_bf<11>(i); return; default: __builtin_unreachable(); } } inline color_t & at(uint16_t x, uint16_t y) { if (on_screen(x, y)) { return Storage::_at(data, x, y); } return junk; } inline color_t & at_unsafe(uint16_t x, uint16_t y) { return Storage::_at(data, x, y); } inline const color_t & at(uint16_t x, uint16_t y) const { if (on_screen(x, y)) { return Storage::_at(data, x, y); } return junk; } inline const color_t & at_unsafe(uint16_t x, uint16_t y) const { return Storage::_at(data, x, y); } inline bool on_screen(uint16_t x, uint16_t y) const { return (x < Width && y < Height); } uint8_t * byte_stream; static constexpr uint16_t width = Width; static constexpr uint16_t effective_width = Storage::EffectiveWidth; static constexpr uint16_t height = Height; static constexpr uint16_t stb_lines = 16; protected: color_t data[Width*Height]; color_t junk; // used as failsafe for read/write out of bounds private: template<unsigned Pos> void prepare_stream_bf(uint16_t i) { uint16_t * lo = &data[i*Storage::EffectiveWidth].r; uint16_t * hi = lo + stb_lines*Storage::EffectiveWidth*3; uint8_t * bs = byte_stream; for (uint_fast16_t j = 0; j < Storage::EffectiveWidth / 2; ++j) { asm volatile ( // Load 3 words (or 6 colors / 2 pixels) into r1-r3 using ldm "ldmia %[Lo]!, {r1,r2,r3}\n\t" // Grab green0 "ubfx r10, r1, %[PosPlus], #1\n\t" // Place red0 (r1 is now g16r "ubfx r1, r1, %[Pos], #1\n\t" // Place red1 "lsr r2, r2, %[Pos]\n\t" // Grab blue0 "bfi r10, r2, #1, #1\n\t" // Mask red0 //"ubfx r1, r1, #1, #1\n\t" // Or into r1 "bfi r1, r10, #1, #2\n\t" /// now r1 contains <junk>bgr in correct order // Extract green1 into r10 "ubfx r10, r3, %[Pos], #1\n\t" // Prepare pixel2 "lsr r3, r3, %[PosPlus]\n\t" // Insert "bfi r10, r3, #1, #1\n\t" // Bfi again to create final value to be orred "bfi r2, r10, #17, #2\n\t" /// now r2 contains <junk>bgr<junk> // Mask out r2 "and r2, r2, #0x00070000\n\t" // Prepare bit sequence "orr r11, r1, r2\n\t" // Load bottom 3 bytes // Load 3 words (or 6 colors / 2 pixels) into r1-r3 using ldm "ldmia %[Hi]!, {r1,r2,r3}\n\t" // Grab green0 "ubfx r10, r1, %[PosPlus], #1\n\t" // Place red0 (r1 is now g16r "ubfx r1, r1, %[Pos], #1\n\t" // Place red1 "lsr r2, r2, %[Pos]\n\t" // Grab blue0 "bfi r10, r2, #1, #1\n\t" // Mask red0 //"ubfx r1, r1, #1, #1\n\t" // Or into r1 "bfi r1, r10, #1, #2\n\t" /// now r1 contains <junk>bgr in correct order // Extract green1 into r10 "ubfx r10, r3, %[Pos], #1\n\t" // Prepare pixel2 "lsr r3, r3, %[PosPlus]\n\t" // Insert "bfi r10, r3, #1, #1\n\t" // Bfi again to create final value to be orred "bfi r2, r10, #17, #2\n\t" /// now r2 contains <junk>bgr<junk> "and r2, r2, #0x00070000\n\t" "orr r10, r1, r2\n\t" // Prepare actual value "orr r11, r11, r10, lsl #3\n\t" "orr r11, r11, r11, lsl #8\n\t" "orr r11, r11, #0x40004000\n\t" // Store value "str r11, [%[Bs]], #4\n\t" : [Lo]"=r"(lo), [Hi]"=r"(hi), [Bs]"=r"(bs) : "0"(lo), "1"(hi), "2"(bs), [Pos]"i"(Pos), [PosPlus]"i"(Pos + 16) : "r1", "r2", "r3", "cc", "r10", "r11" ); } } }; struct FourPanelSnake { //6<------------------------ //5<------------------------ //4<------------------------ //1------------------------> //2------------------------> //3------------------------> const static uint_fast16_t EffectiveWidth = 256; inline static color_t & _at(color_t * data, uint_fast16_t x, uint_fast16_t y) { x = 127 - x; y = 63 - y; return data[(x + (y / 32)*128) + (y & 31)*EffectiveWidth]; } inline static const color_t & _at(const color_t * data, uint_fast16_t x, uint_fast16_t y) { x = 127 - x; y = 63 - y; return data[(x + (y / 32)*128) + (y & 31)*EffectiveWidth]; } }; template<typename FB> struct Matrix { typedef FB framebuffer_type; Matrix() : fb0(), fb1() { fb0.byte_stream = this->dma_buffer; fb1.byte_stream = this->dma_buffer; } void init() { // Enable clocks LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_TIM1); // timer LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM4); LL_AHB1_GRP1_EnableClock(SIGN_GPIO_PERIPH | LL_AHB1_GRP1_PERIPH_GPIOB | LL_AHB1_GRP1_PERIPH_DMA2); // gpios // Setup the timer. LL_TIM_InitTypeDef tim_init = {0}; tim_init.Prescaler = 3; // Set the timer to run at around 6Mhz, since it's stupid to do it any faster tim_init.Autoreload = 1; tim_init.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; LL_TIM_Init(TIM1, &tim_init); tim_init.Prescaler = 2; tim_init.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1; LL_TIM_Init(TIM4, &tim_init); LL_TIM_EnableDMAReq_UPDATE(TIM1); // trigger dma requests every cycle of tim1 // setup gpios LL_GPIO_InitTypeDef gpio_init = {0}; gpio_init.Pin = LL_GPIO_PIN_0 | LL_GPIO_PIN_1 | LL_GPIO_PIN_2 | LL_GPIO_PIN_3 | LL_GPIO_PIN_4 | LL_GPIO_PIN_5 | LL_GPIO_PIN_6 | LL_GPIO_PIN_7; gpio_init.Mode = LL_GPIO_MODE_OUTPUT; gpio_init.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; gpio_init.OutputType = LL_GPIO_OUTPUT_PUSHPULL; gpio_init.Pull = LL_GPIO_PULL_DOWN; LL_GPIO_Init(SIGN_DATA_Port, &gpio_init); gpio_init.Pin = LL_GPIO_PIN_0 | LL_GPIO_PIN_1 | LL_GPIO_PIN_2 | LL_GPIO_PIN_3 | LL_GPIO_PIN_4 | LL_GPIO_PIN_5; gpio_init.Pull = LL_GPIO_PULL_NO; LL_GPIO_Init(GPIOB, &gpio_init); gpio_init.Pin = LL_GPIO_PIN_6; gpio_init.Alternate = LL_GPIO_AF_2; gpio_init.Mode = LL_GPIO_MODE_ALTERNATE; LL_GPIO_Init(GPIOB, &gpio_init); // enable interrupt on oe wait finish LL_TIM_EnableIT_UPDATE(TIM4); LL_TIM_OC_InitTypeDef tim_oc_init = {0}; tim_oc_init.CompareValue = 1; // compare to 1 tim_oc_init.OCMode = LL_TIM_OCMODE_PWM2; // output active while value is not less than 1 tim_oc_init.OCPolarity = LL_TIM_OCPOLARITY_LOW; // output is active low tim_oc_init.OCState = LL_TIM_OCSTATE_ENABLE; // channel is enabled LL_TIM_OC_Init(TIM4, LL_TIM_CHANNEL_CH1, &tim_oc_init); // set one pulse mode LL_TIM_SetOnePulseMode(TIM4, LL_TIM_ONEPULSEMODE_SINGLE); // Setup le dma LL_DMA_SetChannelSelection(DMA2, LL_DMA_STREAM_5, LL_DMA_CHANNEL_6); LL_DMA_SetDataTransferDirection(DMA2, LL_DMA_STREAM_5, LL_DMA_DIRECTION_MEMORY_TO_PERIPH); LL_DMA_SetStreamPriorityLevel(DMA2, LL_DMA_STREAM_5, LL_DMA_PRIORITY_VERYHIGH); LL_DMA_SetMode(DMA2, LL_DMA_STREAM_5, LL_DMA_MODE_NORMAL); LL_DMA_SetPeriphIncMode(DMA2, LL_DMA_STREAM_5, LL_DMA_PERIPH_NOINCREMENT); LL_DMA_SetMemoryIncMode(DMA2, LL_DMA_STREAM_5, LL_DMA_MEMORY_INCREMENT); LL_DMA_SetPeriphSize(DMA2, LL_DMA_STREAM_5, LL_DMA_PDATAALIGN_BYTE); LL_DMA_SetMemorySize(DMA2, LL_DMA_STREAM_5, LL_DMA_MDATAALIGN_BYTE); LL_DMA_DisableFifoMode(DMA2, LL_DMA_STREAM_5); LL_DMA_DisableIT_HT(DMA2, LL_DMA_STREAM_5); LL_DMA_EnableIT_TC(DMA2, LL_DMA_STREAM_5); LL_DMA_EnableIT_TE(DMA2, LL_DMA_STREAM_5); } void start_display() { // Set config values back to sane defaults pos = 0; row = 0; show = true; delaying = false; should_swap = false; delay_counter = 0; // update timer mode to blank screen / proper LL_TIM_OC_SetMode(TIM4, LL_TIM_CHANNEL_CH1, force_off ? LL_TIM_OCMODE_FORCED_INACTIVE : LL_TIM_OCMODE_PWM2); // start the whole procedure blast_row(); } // This should only be called from an RTOS task void swap_buffers() { //active_buffer = !active_buffer; notify_when_swapped = xTaskGetCurrentTaskHandle(); should_swap = true; // This uses the task notification value to wait for something to happen. // This _does_ preclude the use of notification values for anything else. xTaskNotifyWait(0, 0xffffffffUL, NULL, portMAX_DELAY); } void swap_buffers_from_isr() { notify_when_swapped = nullptr; should_swap = true; while (should_swap) {;} } FB& get_inactive_buffer() {return active_buffer ? fb1 : fb0;} const FB& get_active_buffer() {return active_buffer ? fb0 : fb1;} void dma_finish() { // blast is finished, stop dma + timer output LL_TIM_DisableCounter(TIM1); LL_DMA_DisableStream(DMA2, LL_DMA_STREAM_5); // check show if (show) do_next(); else show = true; } void tim_elapsed() { if (!delaying) return; // we don't bother clearing counter enable since OPM will do it for us. delaying = false; if (show) do_next(); else { show = true; } } int16_t frames_without_refresh = 0; volatile bool force_off = false; private: FB fb0, fb1; bool active_buffer = false; uint8_t pos = 0; uint16_t row = 0; uint8_t dma_buffer[(FB::effective_width * 2) + 3]; TaskHandle_t notify_when_swapped = nullptr; // impl for the wait system uint16_t delay_counter = 0; bool delaying = false; // show variable bool show = false; // should swap buffers bool should_swap = false; // pins gpio::Pin<GPIOB_BASE, 5> strobe; // clock is tied to tim2_ch3 FB& _get_active_buffer() {return active_buffer ? fb0 : fb1;} void blast_row() { LL_DMA_ConfigAddresses(DMA2, LL_DMA_STREAM_5, (uint32_t)dma_buffer, (uint32_t)(&SIGN_DATA_Port->ODR), LL_DMA_DIRECTION_MEMORY_TO_PERIPH); LL_DMA_SetDataLength(DMA2, LL_DMA_STREAM_5, (FB::effective_width * 2) + 1); // make sure the active buffer is ready _get_active_buffer().prepare_stream(row, pos); LL_DMA_EnableStream(DMA2, LL_DMA_STREAM_5); // blasting is a-go LL_TIM_SetCounter(TIM1, 0); LL_TIM_EnableCounter(TIM1); } void wait(uint16_t ticks) { if (delaying) return; // set the counter delaying = true; delay_counter = (ticks); // enable the ticker (happens every 3 ticks of tim1, compute based on width * 3 * amt) LL_TIM_SetCounter(TIM4, 0); // this isn't really necessary but may as well LL_TIM_SetAutoReload(TIM4, ticks); // 1 tick for the 0 state. LL_TIM_EnableCounter(TIM4); } void do_next() { const static uint16_t draw_ticks_table[] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; show = false; uint16_t drawn_pos = draw_ticks_table[pos]; // set address pins if (pos == 12) { // We have finished clocking out a row, process buffer swaps if (should_swap) { active_buffer = !active_buffer; if (notify_when_swapped) xTaskNotifyFromISR(notify_when_swapped, 1, eSetValueWithOverwrite, NULL); should_swap = false; frames_without_refresh = 0; } else { frames_without_refresh += 1; } // Start the display again start_display(); return; } strobe = true; // Thing GPIOB->ODR = (GPIOB->ODR & 0xfff0) | (row & 0x000f); ++row; if (row < FB::stb_lines) { strobe = false; // Send off the next row blast_row(); // Start the waiting. wait(drawn_pos); return; } else if (++pos < 12) { strobe = false; // Set back to first row row = 0; // Blast and wait blast_row(); wait(drawn_pos); return; } else { strobe = false; // Alright, pos == 12, so run the wait code // Just wait, but force it to run us again. show = true; wait(drawn_pos); } } }; } #endif
mincrmatt12/MSign
stm/src/tasks/screen.h
<filename>stm/src/tasks/screen.h #ifndef MSN_SCREEN_H #define MSN_SCREEN_H #include "../screens/base.h" #include "../screens/ttc.h" #include "../screens/weather.h" #include "../screens/clock.h" #include "../screens/threed.h" namespace tasks { struct DispMan { void run(); bool interacting() const { return interact_timeout && interact_mode; } private: screen::ScreenSwapper< screen::TTCScreen, screen::WeatherScreen, screen::LayeredScreen< threed::Renderer, screen::ClockScreen > > swapper; uint8_t screen_list_idx = 0; enum InteractMode : uint8_t { InteractNone = 0, InteractByScreen = 1, InteractMenuOpen = 2, InteractOverrideScreen = 3 } interact_mode = InteractNone; // todo: put this in a union // uint8_t menu_id, menu_selection; -- put this to a separate class thingy uint64_t last_swapped_at = 0; uint32_t interact_timeout = 0; TickType_t last_had_wifi_at = 0; bool early_transition_informed = false; struct MS { uint8_t selected = 0; enum Submenu : uint8_t { SubmenuMain = 0, SubmenuConnInfo = 1, SubmenuSelectScreen = 2, SubmenuDebug = 3 } submenu = SubmenuMain; void reset() { new (this) MS{}; } } ms; int next_screen_idx(bool prev=false); void draw_conn_panel(); void draw_menu_list(const char * const * entries, bool last_is_close=true); void do_menu_overlay(); void do_sleep_mode(); }; } #endif
mincrmatt12/MSign
esp/main/json.h
<reponame>mincrmatt12/MSign #ifndef JSON_H #define JSON_H #include <cstdlib> #include <cstdint> #include <functional> #include "dwhttp.h" namespace json { struct PathNode { char * name = nullptr; uint16_t index; bool array; PathNode() {} PathNode(char * name_in) : name(name_in), index(0), array(false) {} PathNode(char * name_in, uint16_t index) : name(name_in), index(index), array(true) {} inline bool is_array() const {return array && !is_root();} inline bool is_root() const {return name == nullptr;} inline bool is_obj() const {return !array && !is_root();} }; struct Value { enum Type : uint8_t { STR, FLOAT, INT, BOOL, NONE, OBJ // technically a none, but called at the end of an object. } type; union { const char* str_val; float float_val; int64_t int_val; bool bool_val; }; Value(Type t=NONE) : type(t) {} Value(float v) : type(FLOAT), float_val(v) {} Value(int64_t v) : type(INT), int_val(v) {} Value(bool b) : type(BOOL), bool_val(b) {} Value(const char * str) : type(STR), str_val(str) {} inline bool is_number() const {return type == FLOAT || type == INT;} inline float as_number() const {return type == FLOAT ? float_val : int_val;} }; typedef std::function<void (PathNode **, uint8_t, const Value&)> JSONCallback; typedef std::function<int16_t (void)> TextCallback; constexpr inline static size_t TreeBlock = 128; struct TreeSlabAllocator { TreeSlabAllocator(); ~TreeSlabAllocator(); // Allocate a single object template<typename T, typename ...Args> T* make(Args&& ...args) { if (!append(nullptr, sizeof(T))) return nullptr; return new (end()) T (std::forward<Args>(args)...); } // Push a character onto a variable length object bool push(uint8_t c); // Returns false if out of memory // Finish a variable length object uint8_t * end(); // Free up the latest allocation void finish(void * obj); private: bool append(const uint8_t * data, size_t amount); size_t offset() { return _start - tail->data; } size_t curlen() { return _last - _start; } struct Chunk { Chunk(Chunk *onto=nullptr) { length = TreeBlock; used = 0; previous = onto; data = (uint8_t *)malloc(TreeBlock); } ~Chunk() { if (data) free(data); if (previous) delete previous; } uint16_t length{}; uint16_t used{}; Chunk * previous{}; uint8_t * data{}; bool expand(size_t to) { length = to; data = (uint8_t *)realloc(data, to); return data; } } *tail; uint8_t *_last, *_start; }; struct JSONParser { JSONParser(JSONCallback && c, bool is_utf8=false); ~JSONParser(); bool parse(const char * text); bool parse(const char * text, size_t size); bool parse(TextCallback && c); #ifndef STANDALONE_JSON bool parse(dwhttp::Download & d); #endif private: PathNode& top() { return *stack[stack_ptr - 1]; } template<typename... Args> inline void push(Args&&... args) { stack[stack_ptr++] = memory.make<PathNode>(std::forward<Args>(args)...); } void pop () { memory.finish(stack[--stack_ptr]); } bool parse_value(); bool parse_object(); bool parse_array(); bool parse_string(); bool parse_number(); bool parse_singleton(); char * parse_string_text(); bool advance_whitespace(); char peek(); char next(); char temp = 0; uint8_t stack_ptr; bool need = true; bool is_utf8 = false; PathNode * stack[20]; JSONCallback cb; TextCallback tcb; TreeSlabAllocator memory; }; } #endif
mincrmatt12/MSign
stm/src/crash/main.h
#ifndef MSN_STCRASH_MAIN_H #define MSN_STCRASH_MAIN_H #include <stdint.h> namespace crash { // Transfer control to the crash handler. // // `errcode` must either be null or point to memory outside of the crash handler's region (i.e. // outside VRAM) // // This function does not return. [[noreturn]] void call_crash_main(const char *errcode, uint32_t SP, uint32_t PC, uint32_t LR) __attribute__((naked)); // Transfer control to the crash handler from an arbitrary point in the code [[noreturn]] __attribute__((always_inline)) void inline panic(const char* errcode) { uint32_t pc, lr, sp; asm volatile ( "mov %0, pc\n\t" "mov %1, lr\n\t" "mov %2, sp\n\t" : "=r" (pc), "=r" (lr), "=r" (sp) ); call_crash_main(errcode, sp, pc, lr); } // Transfer control to the crash handler but don't show a backtrace / debug screen, just show a short message and reboot automatically. // // This is the same as setting PC to 0xffff ffff and SP to 0 [[noreturn]] void panic_nonfatal(const char* errcode); // Transfer control the interrupt handler, getting the state from the stacked registers in an interrupt handler. [[noreturn]] void panic_from_isr(const char* errcode, uint32_t *SP_at_ISR_entry); }; extern "C" void msign_assert(bool condition, const char *msg="assertion failed"); #endif
mincrmatt12/MSign
esp/components/libb64/cencode.c
/* cencoder.c - c source to a base64 encoding algorithm implementation This is part of the libb64 project, and has been placed in the public domain. For details, see http://sourceforge.net/projects/libb64 */ #include <b64/cencode.h> void base64_init_encodestate(base64_encodestate* state_in) { state_in->step = step_A; state_in->result = 0; state_in->stepcount = 0; state_in->chars_per_line = BASE64_CENC_DEFCPL; } /* * Calculate required length of buffer for encoded string when using encoder state structure state_in for encoding * and when having input data of size plain_len * * Return encoded length, or 0 if encoded length + one additional null byte would exceed range of size_t */ size_t base64_encode_length(size_t plain_len, base64_encodestate* state_in) { size_t retmax = 0, retval; size_t cpl = state_in->chars_per_line; /* * Check for integer overflow. Takes into consideration that gcc may optimise out * naive integer overflow checks based on the C standard saying the result of overflow is undefined. */ retmax = ~retmax; retval = (plain_len + 2) / 3; if(retval > retmax / 4) return 0; retval *= 4; /* Calculate number of linebreaks */ if(retval && cpl) { size_t numbreaks; numbreaks = (retval - 1) / cpl + 1; retmax -= retval; /* Make sure there's always room for one additional 0 byte on top of our return value */ if(numbreaks < retmax) return numbreaks + retval; else return 0; } else return retval; } char base64_encode_value(signed char value_in) { static const char* encoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; if (value_in > 63) return '='; return encoding[(int)value_in]; } #define CHECK_BREAK() \ do \ { \ if (cpl && state_in->stepcount >= cpl) \ { \ *codechar++ = '\n'; \ state_in->stepcount = 0; \ } \ state_in->stepcount++; \ } while(0); size_t base64_encode_block(const void* plaintext_in, const size_t length_in, char* code_out, base64_encodestate* state_in) { const char* plainchar = plaintext_in; const char* const plaintextend = plainchar + length_in; char* codechar = code_out; size_t cpl = state_in->chars_per_line; char result; char fragment; result = state_in->result; switch (state_in->step) { for(;;) { case step_A: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_A; return (size_t)(codechar - code_out); } CHECK_BREAK(); fragment = *plainchar++; result = (fragment & 0x0fc) >> 2; *codechar++ = base64_encode_value(result); result = (fragment & 0x003) << 4; case step_B: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_B; return (size_t)(codechar - code_out); } CHECK_BREAK(); fragment = *plainchar++; result |= (fragment & 0x0f0) >> 4; *codechar++ = base64_encode_value(result); result = (fragment & 0x00f) << 2; case step_C: if (plainchar == plaintextend) { state_in->result = result; state_in->step = step_C; return (size_t)(codechar - code_out); } CHECK_BREAK(); fragment = *plainchar++; result |= (fragment & 0x0c0) >> 6; *codechar++ = base64_encode_value(result); CHECK_BREAK(); result = (fragment & 0x03f) >> 0; *codechar++ = base64_encode_value(result); } } /* control should not reach here */ return (size_t) (codechar - code_out); } size_t base64_encode_blockend(char* code_out, base64_encodestate* state_in) { char* codechar = code_out; size_t cpl = state_in->chars_per_line; switch (state_in->step) { case step_B: CHECK_BREAK(); *codechar++ = base64_encode_value(state_in->result); CHECK_BREAK(); *codechar++ = '='; CHECK_BREAK(); *codechar++ = '='; break; case step_C: CHECK_BREAK(); *codechar++ = base64_encode_value(state_in->result); CHECK_BREAK(); *codechar++ = '='; break; case step_A: break; } if(state_in->chars_per_line) *codechar++ = '\n'; return (size_t) (codechar - code_out); }
mincrmatt12/MSign
esp/main/webui.h
<gh_stars>1-10 #ifndef WEBUI_H #define WEBUI_H namespace webui { void run(void*); } #endif
mincrmatt12/MSign
sim/src/esp/esp8266/eagle_soc.h
#pragma once // NOTE: THIS WILL CAUSE MEMORY LEAKS IN CONFIG; i don't care enough to fix this #define IS_DRAM(x) false #define IS_IRAM(x) false