Skip to content
Snippets Groups Projects
pugixml.cpp 266 KiB
Newer Older
  • Learn to ignore specific revisions
  • Radim Vavřík's avatar
    Radim Vavřík committed
    3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000
    			writer.write(prev, static_cast<size_t>(s - prev));
    
    			switch (*s)
    			{
    				case 0: break;
    				case '&':
    					writer.write('&', 'a', 'm', 'p', ';');
    					++s;
    					break;
    				case '<':
    					writer.write('&', 'l', 't', ';');
    					++s;
    					break;
    				case '>':
    					writer.write('&', 'g', 't', ';');
    					++s;
    					break;
    				case '"':
    					writer.write('&', 'q', 'u', 'o', 't', ';');
    					++s;
    					break;
    				default: // s is not a usual symbol
    				{
    					unsigned int ch = static_cast<unsigned int>(*s++);
    					assert(ch < 32);
    
    					writer.write('&', '#', static_cast<char_t>((ch / 10) + '0'), static_cast<char_t>((ch % 10) + '0'), ';');
    				}
    			}
    		}
    	}
    
    	PUGI__FN void text_output(xml_buffered_writer& writer, const char_t* s, chartypex_t type, unsigned int flags)
    	{
    		if (flags & format_no_escapes)
    			writer.write(s);
    		else
    			text_output_escaped(writer, s, type);
    	}
    
    	PUGI__FN void text_output_cdata(xml_buffered_writer& writer, const char_t* s)
    	{
    		do
    		{
    			writer.write('<', '!', '[', 'C', 'D');
    			writer.write('A', 'T', 'A', '[');
    
    			const char_t* prev = s;
    
    			// look for ]]> sequence - we can't output it as is since it terminates CDATA
    			while (*s && !(s[0] == ']' && s[1] == ']' && s[2] == '>')) ++s;
    
    			// skip ]] if we stopped at ]]>, > will go to the next CDATA section
    			if (*s) s += 2;
    
    			writer.write(prev, static_cast<size_t>(s - prev));
    
    			writer.write(']', ']', '>');
    		}
    		while (*s);
    	}
    
    	PUGI__FN void node_output_attributes(xml_buffered_writer& writer, const xml_node& node, unsigned int flags)
    	{
    		const char_t* default_name = PUGIXML_TEXT(":anonymous");
    
    		for (xml_attribute a = node.first_attribute(); a; a = a.next_attribute())
    		{
    			writer.write(' ');
    			writer.write(a.name()[0] ? a.name() : default_name);
    			writer.write('=', '"');
    
    			text_output(writer, a.value(), ctx_special_attr, flags);
    
    			writer.write('"');
    		}
    	}
    
    	PUGI__FN void node_output(xml_buffered_writer& writer, const xml_node& node, const char_t* indent, unsigned int flags, unsigned int depth)
    	{
    		const char_t* default_name = PUGIXML_TEXT(":anonymous");
    
    		if ((flags & format_indent) != 0 && (flags & format_raw) == 0)
    			for (unsigned int i = 0; i < depth; ++i) writer.write(indent);
    
    		switch (node.type())
    		{
    		case node_document:
    		{
    			for (xml_node n = node.first_child(); n; n = n.next_sibling())
    				node_output(writer, n, indent, flags, depth);
    			break;
    		}
    			
    		case node_element:
    		{
    			const char_t* name = node.name()[0] ? node.name() : default_name;
    
    			writer.write('<');
    			writer.write(name);
    
    			node_output_attributes(writer, node, flags);
    
    			if (flags & format_raw)
    			{
    				if (!node.first_child())
    					writer.write(' ', '/', '>');
    				else
    				{
    					writer.write('>');
    
    					for (xml_node n = node.first_child(); n; n = n.next_sibling())
    						node_output(writer, n, indent, flags, depth + 1);
    
    					writer.write('<', '/');
    					writer.write(name);
    					writer.write('>');
    				}
    			}
    			else if (!node.first_child())
    				writer.write(' ', '/', '>', '\n');
    			else if (node.first_child() == node.last_child() && (node.first_child().type() == node_pcdata || node.first_child().type() == node_cdata))
    			{
    				writer.write('>');
    
    				if (node.first_child().type() == node_pcdata)
    					text_output(writer, node.first_child().value(), ctx_special_pcdata, flags);
    				else
    					text_output_cdata(writer, node.first_child().value());
    
    				writer.write('<', '/');
    				writer.write(name);
    				writer.write('>', '\n');
    			}
    			else
    			{
    				writer.write('>', '\n');
    				
    				for (xml_node n = node.first_child(); n; n = n.next_sibling())
    					node_output(writer, n, indent, flags, depth + 1);
    
    				if ((flags & format_indent) != 0 && (flags & format_raw) == 0)
    					for (unsigned int i = 0; i < depth; ++i) writer.write(indent);
    				
    				writer.write('<', '/');
    				writer.write(name);
    				writer.write('>', '\n');
    			}
    
    			break;
    		}
    		
    		case node_pcdata:
    			text_output(writer, node.value(), ctx_special_pcdata, flags);
    			if ((flags & format_raw) == 0) writer.write('\n');
    			break;
    
    		case node_cdata:
    			text_output_cdata(writer, node.value());
    			if ((flags & format_raw) == 0) writer.write('\n');
    			break;
    
    		case node_comment:
    			writer.write('<', '!', '-', '-');
    			writer.write(node.value());
    			writer.write('-', '-', '>');
    			if ((flags & format_raw) == 0) writer.write('\n');
    			break;
    
    		case node_pi:
    		case node_declaration:
    			writer.write('<', '?');
    			writer.write(node.name()[0] ? node.name() : default_name);
    
    			if (node.type() == node_declaration)
    			{
    				node_output_attributes(writer, node, flags);
    			}
    			else if (node.value()[0])
    			{
    				writer.write(' ');
    				writer.write(node.value());
    			}
    
    			writer.write('?', '>');
    			if ((flags & format_raw) == 0) writer.write('\n');
    			break;
    
    		case node_doctype:
    			writer.write('<', '!', 'D', 'O', 'C');
    			writer.write('T', 'Y', 'P', 'E');
    
    			if (node.value()[0])
    			{
    				writer.write(' ');
    				writer.write(node.value());
    			}
    
    			writer.write('>');
    			if ((flags & format_raw) == 0) writer.write('\n');
    			break;
    
    		default:
    			assert(!"Invalid node type");
    		}
    	}
    
    	inline bool has_declaration(const xml_node& node)
    	{
    		for (xml_node child = node.first_child(); child; child = child.next_sibling())
    		{
    			xml_node_type type = child.type();
    
    			if (type == node_declaration) return true;
    			if (type == node_element) return false;
    		}
    
    		return false;
    	}
    
    	inline bool allow_insert_child(xml_node_type parent, xml_node_type child)
    	{
    		if (parent != node_document && parent != node_element) return false;
    		if (child == node_document || child == node_null) return false;
    		if (parent != node_document && (child == node_declaration || child == node_doctype)) return false;
    
    		return true;
    	}
    
    	PUGI__FN void recursive_copy_skip(xml_node& dest, const xml_node& source, const xml_node& skip)
    	{
    		assert(dest.type() == source.type());
    
    		switch (source.type())
    		{
    		case node_element:
    		{
    			dest.set_name(source.name());
    
    			for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())
    				dest.append_attribute(a.name()).set_value(a.value());
    
    			for (xml_node c = source.first_child(); c; c = c.next_sibling())
    			{
    				if (c == skip) continue;
    
    				xml_node cc = dest.append_child(c.type());
    				assert(cc);
    
    				recursive_copy_skip(cc, c, skip);
    			}
    
    			break;
    		}
    
    		case node_pcdata:
    		case node_cdata:
    		case node_comment:
    		case node_doctype:
    			dest.set_value(source.value());
    			break;
    
    		case node_pi:
    			dest.set_name(source.name());
    			dest.set_value(source.value());
    			break;
    
    		case node_declaration:
    		{
    			dest.set_name(source.name());
    
    			for (xml_attribute a = source.first_attribute(); a; a = a.next_attribute())
    				dest.append_attribute(a.name()).set_value(a.value());
    
    			break;
    		}
    
    		default:
    			assert(!"Invalid node type");
    		}
    	}
    
    	inline bool is_text_node(xml_node_struct* node)
    	{
    		xml_node_type type = static_cast<xml_node_type>((node->header & impl::xml_memory_page_type_mask) + 1);
    
    		return type == node_pcdata || type == node_cdata;
    	}
    
    	// get value with conversion functions
    	PUGI__FN int get_value_int(const char_t* value, int def)
    	{
    		if (!value) return def;
    
    	#ifdef PUGIXML_WCHAR_MODE
    		return static_cast<int>(wcstol(value, 0, 10));
    	#else
    		return static_cast<int>(strtol(value, 0, 10));
    	#endif
    	}
    
    	PUGI__FN unsigned int get_value_uint(const char_t* value, unsigned int def)
    	{
    		if (!value) return def;
    
    	#ifdef PUGIXML_WCHAR_MODE
    		return static_cast<unsigned int>(wcstoul(value, 0, 10));
    	#else
    		return static_cast<unsigned int>(strtoul(value, 0, 10));
    	#endif
    	}
    
    	PUGI__FN double get_value_double(const char_t* value, double def)
    	{
    		if (!value) return def;
    
    	#ifdef PUGIXML_WCHAR_MODE
    		return wcstod(value, 0);
    	#else
    		return strtod(value, 0);
    	#endif
    	}
    
    	PUGI__FN float get_value_float(const char_t* value, float def)
    	{
    		if (!value) return def;
    
    	#ifdef PUGIXML_WCHAR_MODE
    		return static_cast<float>(wcstod(value, 0));
    	#else
    		return static_cast<float>(strtod(value, 0));
    	#endif
    	}
    
    	PUGI__FN bool get_value_bool(const char_t* value, bool def)
    	{
    		if (!value) return def;
    
    		// only look at first char
    		char_t first = *value;
    
    		// 1*, t* (true), T* (True), y* (yes), Y* (YES)
    		return (first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
    	}
    
    	// set value with conversion functions
    	PUGI__FN bool set_value_buffer(char_t*& dest, uintptr_t& header, uintptr_t header_mask, char (&buf)[128])
    	{
    	#ifdef PUGIXML_WCHAR_MODE
    		char_t wbuf[128];
    		impl::widen_ascii(wbuf, buf);
    
    		return strcpy_insitu(dest, header, header_mask, wbuf);
    	#else
    		return strcpy_insitu(dest, header, header_mask, buf);
    	#endif
    	}
    
    	PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, int value)
    	{
    		char buf[128];
    		sprintf(buf, "%d", value);
    	
    		return set_value_buffer(dest, header, header_mask, buf);
    	}
    
    	PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, unsigned int value)
    	{
    		char buf[128];
    		sprintf(buf, "%u", value);
    
    		return set_value_buffer(dest, header, header_mask, buf);
    	}
    
    	PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, double value)
    	{
    		char buf[128];
    		sprintf(buf, "%g", value);
    
    		return set_value_buffer(dest, header, header_mask, buf);
    	}
    	
    	PUGI__FN bool set_value_convert(char_t*& dest, uintptr_t& header, uintptr_t header_mask, bool value)
    	{
    		return strcpy_insitu(dest, header, header_mask, value ? PUGIXML_TEXT("true") : PUGIXML_TEXT("false"));
    	}
    
    	// we need to get length of entire file to load it in memory; the only (relatively) sane way to do it is via seek/tell trick
    	PUGI__FN xml_parse_status get_file_size(FILE* file, size_t& out_result)
    	{
    	#if defined(PUGI__MSVC_CRT_VERSION) && PUGI__MSVC_CRT_VERSION >= 1400 && !defined(_WIN32_WCE)
    		// there are 64-bit versions of fseek/ftell, let's use them
    		typedef __int64 length_type;
    
    		_fseeki64(file, 0, SEEK_END);
    		length_type length = _ftelli64(file);
    		_fseeki64(file, 0, SEEK_SET);
    	#elif defined(__MINGW32__) && !defined(__NO_MINGW_LFS) && !defined(__STRICT_ANSI__)
    		// there are 64-bit versions of fseek/ftell, let's use them
    		typedef off64_t length_type;
    
    		fseeko64(file, 0, SEEK_END);
    		length_type length = ftello64(file);
    		fseeko64(file, 0, SEEK_SET);
    	#else
    		// if this is a 32-bit OS, long is enough; if this is a unix system, long is 64-bit, which is enough; otherwise we can't do anything anyway.
    		typedef long length_type;
    
    		fseek(file, 0, SEEK_END);
    		length_type length = ftell(file);
    		fseek(file, 0, SEEK_SET);
    	#endif
    
    		// check for I/O errors
    		if (length < 0) return status_io_error;
    		
    		// check for overflow
    		size_t result = static_cast<size_t>(length);
    
    		if (static_cast<length_type>(result) != length) return status_out_of_memory;
    
    		// finalize
    		out_result = result;
    
    		return status_ok;
    	}
    
    	PUGI__FN xml_parse_result load_file_impl(xml_document& doc, FILE* file, unsigned int options, xml_encoding encoding)
    	{
    		if (!file) return make_parse_result(status_file_not_found);
    
    		// get file size (can result in I/O errors)
    		size_t size = 0;
    		xml_parse_status size_status = get_file_size(file, size);
    
    		if (size_status != status_ok)
    		{
    			fclose(file);
    			return make_parse_result(size_status);
    		}
    		
    		// allocate buffer for the whole file
    		char* contents = static_cast<char*>(xml_memory::allocate(size > 0 ? size : 1));
    
    		if (!contents)
    		{
    			fclose(file);
    			return make_parse_result(status_out_of_memory);
    		}
    
    		// read file in memory
    		size_t read_size = fread(contents, 1, size, file);
    		fclose(file);
    
    		if (read_size != size)
    		{
    			xml_memory::deallocate(contents);
    			return make_parse_result(status_io_error);
    		}
    		
    		return doc.load_buffer_inplace_own(contents, size, options, encoding);
    	}
    
    #ifndef PUGIXML_NO_STL
    	template <typename T> struct xml_stream_chunk
    	{
    		static xml_stream_chunk* create()
    		{
    			void* memory = xml_memory::allocate(sizeof(xml_stream_chunk));
    			
    			return new (memory) xml_stream_chunk();
    		}
    
    		static void destroy(void* ptr)
    		{
    			xml_stream_chunk* chunk = static_cast<xml_stream_chunk*>(ptr);
    
    			// free chunk chain
    			while (chunk)
    			{
    				xml_stream_chunk* next = chunk->next;
    				xml_memory::deallocate(chunk);
    				chunk = next;
    			}
    		}
    
    		xml_stream_chunk(): next(0), size(0)
    		{
    		}
    
    		xml_stream_chunk* next;
    		size_t size;
    
    		T data[xml_memory_page_size / sizeof(T)];
    	};
    
    	template <typename T> PUGI__FN xml_parse_status load_stream_data_noseek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
    	{
    		buffer_holder chunks(0, xml_stream_chunk<T>::destroy);
    
    		// read file to a chunk list
    		size_t total = 0;
    		xml_stream_chunk<T>* last = 0;
    
    		while (!stream.eof())
    		{
    			// allocate new chunk
    			xml_stream_chunk<T>* chunk = xml_stream_chunk<T>::create();
    			if (!chunk) return status_out_of_memory;
    
    			// append chunk to list
    			if (last) last = last->next = chunk;
    			else chunks.data = last = chunk;
    
    			// read data to chunk
    			stream.read(chunk->data, static_cast<std::streamsize>(sizeof(chunk->data) / sizeof(T)));
    			chunk->size = static_cast<size_t>(stream.gcount()) * sizeof(T);
    
    			// read may set failbit | eofbit in case gcount() is less than read length, so check for other I/O errors
    			if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
    
    			// guard against huge files (chunk size is small enough to make this overflow check work)
    			if (total + chunk->size < total) return status_out_of_memory;
    			total += chunk->size;
    		}
    
    		// copy chunk list to a contiguous buffer
    		char* buffer = static_cast<char*>(xml_memory::allocate(total));
    		if (!buffer) return status_out_of_memory;
    
    		char* write = buffer;
    
    		for (xml_stream_chunk<T>* chunk = static_cast<xml_stream_chunk<T>*>(chunks.data); chunk; chunk = chunk->next)
    		{
    			assert(write + chunk->size <= buffer + total);
    			memcpy(write, chunk->data, chunk->size);
    			write += chunk->size;
    		}
    
    		assert(write == buffer + total);
    
    		// return buffer
    		*out_buffer = buffer;
    		*out_size = total;
    
    		return status_ok;
    	}
    
    	template <typename T> PUGI__FN xml_parse_status load_stream_data_seek(std::basic_istream<T>& stream, void** out_buffer, size_t* out_size)
    	{
    		// get length of remaining data in stream
    		typename std::basic_istream<T>::pos_type pos = stream.tellg();
    		stream.seekg(0, std::ios::end);
    		std::streamoff length = stream.tellg() - pos;
    		stream.seekg(pos);
    
    		if (stream.fail() || pos < 0) return status_io_error;
    
    		// guard against huge files
    		size_t read_length = static_cast<size_t>(length);
    
    		if (static_cast<std::streamsize>(read_length) != length || length < 0) return status_out_of_memory;
    
    		// read stream data into memory (guard against stream exceptions with buffer holder)
    		buffer_holder buffer(xml_memory::allocate((read_length > 0 ? read_length : 1) * sizeof(T)), xml_memory::deallocate);
    		if (!buffer.data) return status_out_of_memory;
    
    		stream.read(static_cast<T*>(buffer.data), static_cast<std::streamsize>(read_length));
    
    		// read may set failbit | eofbit in case gcount() is less than read_length (i.e. line ending conversion), so check for other I/O errors
    		if (stream.bad() || (!stream.eof() && stream.fail())) return status_io_error;
    
    		// return buffer
    		size_t actual_length = static_cast<size_t>(stream.gcount());
    		assert(actual_length <= read_length);
    
    		*out_buffer = buffer.release();
    		*out_size = actual_length * sizeof(T);
    
    		return status_ok;
    	}
    
    	template <typename T> PUGI__FN xml_parse_result load_stream_impl(xml_document& doc, std::basic_istream<T>& stream, unsigned int options, xml_encoding encoding)
    	{
    		void* buffer = 0;
    		size_t size = 0;
    
    		// load stream to memory (using seek-based implementation if possible, since it's faster and takes less memory)
    		xml_parse_status status = (stream.tellg() < 0) ? load_stream_data_noseek(stream, &buffer, &size) : load_stream_data_seek(stream, &buffer, &size);
    		if (status != status_ok) return make_parse_result(status);
    
    		return doc.load_buffer_inplace_own(buffer, size, options, encoding);
    	}
    #endif
    
    #if defined(PUGI__MSVC_CRT_VERSION) || defined(__BORLANDC__) || (defined(__MINGW32__) && !defined(__STRICT_ANSI__))
    	PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
    	{
    		return _wfopen(path, mode);
    	}
    #else
    	PUGI__FN char* convert_path_heap(const wchar_t* str)
    	{
    		assert(str);
    
    		// first pass: get length in utf8 characters
    		size_t length = wcslen(str);
    		size_t size = as_utf8_begin(str, length);
    
    		// allocate resulting string
    		char* result = static_cast<char*>(xml_memory::allocate(size + 1));
    		if (!result) return 0;
    
    		// second pass: convert to utf8
    		as_utf8_end(result, size, str, length);
    
    		return result;
    	}
    
    	PUGI__FN FILE* open_file_wide(const wchar_t* path, const wchar_t* mode)
    	{
    		// there is no standard function to open wide paths, so our best bet is to try utf8 path
    		char* path_utf8 = convert_path_heap(path);
    		if (!path_utf8) return 0;
    
    		// convert mode to ASCII (we mirror _wfopen interface)
    		char mode_ascii[4] = {0};
    		for (size_t i = 0; mode[i]; ++i) mode_ascii[i] = static_cast<char>(mode[i]);
    
    		// try to open the utf8 path
    		FILE* result = fopen(path_utf8, mode_ascii);
    
    		// free dummy buffer
    		xml_memory::deallocate(path_utf8);
    
    		return result;
    	}
    #endif
    
    	PUGI__FN bool save_file_impl(const xml_document& doc, FILE* file, const char_t* indent, unsigned int flags, xml_encoding encoding)
    	{
    		if (!file) return false;
    
    		xml_writer_file writer(file);
    		doc.save(writer, indent, flags, encoding);
    
    		int result = ferror(file);
    
    		fclose(file);
    
    		return result == 0;
    	}
    PUGI__NS_END
    
    namespace pugi
    {
    	PUGI__FN xml_writer_file::xml_writer_file(void* file_): file(file_)
    	{
    	}
    
    	PUGI__FN void xml_writer_file::write(const void* data, size_t size)
    	{
    		size_t result = fwrite(data, 1, size, static_cast<FILE*>(file));
    		(void)!result; // unfortunately we can't do proper error handling here
    	}
    
    #ifndef PUGIXML_NO_STL
    	PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<char, std::char_traits<char> >& stream): narrow_stream(&stream), wide_stream(0)
    	{
    	}
    
    	PUGI__FN xml_writer_stream::xml_writer_stream(std::basic_ostream<wchar_t, std::char_traits<wchar_t> >& stream): narrow_stream(0), wide_stream(&stream)
    	{
    	}
    
    	PUGI__FN void xml_writer_stream::write(const void* data, size_t size)
    	{
    		if (narrow_stream)
    		{
    			assert(!wide_stream);
    			narrow_stream->write(reinterpret_cast<const char*>(data), static_cast<std::streamsize>(size));
    		}
    		else
    		{
    			assert(wide_stream);
    			assert(size % sizeof(wchar_t) == 0);
    
    			wide_stream->write(reinterpret_cast<const wchar_t*>(data), static_cast<std::streamsize>(size / sizeof(wchar_t)));
    		}
    	}
    #endif
    
    	PUGI__FN xml_tree_walker::xml_tree_walker(): _depth(0)
    	{
    	}
    	
    	PUGI__FN xml_tree_walker::~xml_tree_walker()
    	{
    	}
    
    	PUGI__FN int xml_tree_walker::depth() const
    	{
    		return _depth;
    	}
    
    	PUGI__FN bool xml_tree_walker::begin(xml_node&)
    	{
    		return true;
    	}
    
    	PUGI__FN bool xml_tree_walker::end(xml_node&)
    	{
    		return true;
    	}
    
    	PUGI__FN xml_attribute::xml_attribute(): _attr(0)
    	{
    	}
    
    	PUGI__FN xml_attribute::xml_attribute(xml_attribute_struct* attr): _attr(attr)
    	{
    	}
    
    	PUGI__FN static void unspecified_bool_xml_attribute(xml_attribute***)
    	{
    	}
    
    	PUGI__FN xml_attribute::operator xml_attribute::unspecified_bool_type() const
    	{
    		return _attr ? unspecified_bool_xml_attribute : 0;
    	}
    
    	PUGI__FN bool xml_attribute::operator!() const
    	{
    		return !_attr;
    	}
    
    	PUGI__FN bool xml_attribute::operator==(const xml_attribute& r) const
    	{
    		return (_attr == r._attr);
    	}
    	
    	PUGI__FN bool xml_attribute::operator!=(const xml_attribute& r) const
    	{
    		return (_attr != r._attr);
    	}
    
    	PUGI__FN bool xml_attribute::operator<(const xml_attribute& r) const
    	{
    		return (_attr < r._attr);
    	}
    	
    	PUGI__FN bool xml_attribute::operator>(const xml_attribute& r) const
    	{
    		return (_attr > r._attr);
    	}
    	
    	PUGI__FN bool xml_attribute::operator<=(const xml_attribute& r) const
    	{
    		return (_attr <= r._attr);
    	}
    	
    	PUGI__FN bool xml_attribute::operator>=(const xml_attribute& r) const
    	{
    		return (_attr >= r._attr);
    	}
    
    	PUGI__FN xml_attribute xml_attribute::next_attribute() const
    	{
    		return _attr ? xml_attribute(_attr->next_attribute) : xml_attribute();
    	}
    
    	PUGI__FN xml_attribute xml_attribute::previous_attribute() const
    	{
    		return _attr && _attr->prev_attribute_c->next_attribute ? xml_attribute(_attr->prev_attribute_c) : xml_attribute();
    	}
    
    	PUGI__FN const char_t* xml_attribute::as_string(const char_t* def) const
    	{
    		return (_attr && _attr->value) ? _attr->value : def;
    	}
    
    	PUGI__FN int xml_attribute::as_int(int def) const
    	{
    		return impl::get_value_int(_attr ? _attr->value : 0, def);
    	}
    
    	PUGI__FN unsigned int xml_attribute::as_uint(unsigned int def) const
    	{
    		return impl::get_value_uint(_attr ? _attr->value : 0, def);
    	}
    
    	PUGI__FN double xml_attribute::as_double(double def) const
    	{
    		return impl::get_value_double(_attr ? _attr->value : 0, def);
    	}
    
    	PUGI__FN float xml_attribute::as_float(float def) const
    	{
    		return impl::get_value_float(_attr ? _attr->value : 0, def);
    	}
    
    	PUGI__FN bool xml_attribute::as_bool(bool def) const
    	{
    		return impl::get_value_bool(_attr ? _attr->value : 0, def);
    	}
    
    	PUGI__FN bool xml_attribute::empty() const
    	{
    		return !_attr;
    	}
    
    	PUGI__FN const char_t* xml_attribute::name() const
    	{
    		return (_attr && _attr->name) ? _attr->name : PUGIXML_TEXT("");
    	}
    
    	PUGI__FN const char_t* xml_attribute::value() const
    	{
    		return (_attr && _attr->value) ? _attr->value : PUGIXML_TEXT("");
    	}
    
    	PUGI__FN size_t xml_attribute::hash_value() const
    	{
    		return static_cast<size_t>(reinterpret_cast<uintptr_t>(_attr) / sizeof(xml_attribute_struct));
    	}
    
    	PUGI__FN xml_attribute_struct* xml_attribute::internal_object() const
    	{
    		return _attr;
    	}
    
    	PUGI__FN xml_attribute& xml_attribute::operator=(const char_t* rhs)
    	{
    		set_value(rhs);
    		return *this;
    	}
    	
    	PUGI__FN xml_attribute& xml_attribute::operator=(int rhs)
    	{
    		set_value(rhs);
    		return *this;
    	}
    
    	PUGI__FN xml_attribute& xml_attribute::operator=(unsigned int rhs)
    	{
    		set_value(rhs);
    		return *this;
    	}
    
    	PUGI__FN xml_attribute& xml_attribute::operator=(double rhs)
    	{
    		set_value(rhs);
    		return *this;
    	}
    	
    	PUGI__FN xml_attribute& xml_attribute::operator=(bool rhs)
    	{
    		set_value(rhs);
    		return *this;
    	}
    
    	PUGI__FN bool xml_attribute::set_name(const char_t* rhs)
    	{
    		if (!_attr) return false;
    		
    		return impl::strcpy_insitu(_attr->name, _attr->header, impl::xml_memory_page_name_allocated_mask, rhs);
    	}
    		
    	PUGI__FN bool xml_attribute::set_value(const char_t* rhs)
    	{
    		if (!_attr) return false;
    
    		return impl::strcpy_insitu(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
    	}
    
    	PUGI__FN bool xml_attribute::set_value(int rhs)
    	{
    		if (!_attr) return false;
    
    		return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
    	}
    
    	PUGI__FN bool xml_attribute::set_value(unsigned int rhs)
    	{
    		if (!_attr) return false;
    
    		return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
    	}
    
    	PUGI__FN bool xml_attribute::set_value(double rhs)
    	{
    		if (!_attr) return false;
    
    		return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
    	}
    	
    	PUGI__FN bool xml_attribute::set_value(bool rhs)
    	{
    		if (!_attr) return false;
    
    		return impl::set_value_convert(_attr->value, _attr->header, impl::xml_memory_page_value_allocated_mask, rhs);
    	}
    
    #ifdef __BORLANDC__
    	PUGI__FN bool operator&&(const xml_attribute& lhs, bool rhs)
    	{
    		return (bool)lhs && rhs;
    	}
    
    	PUGI__FN bool operator||(const xml_attribute& lhs, bool rhs)
    	{
    		return (bool)lhs || rhs;
    	}
    #endif
    
    	PUGI__FN xml_node::xml_node(): _root(0)
    	{
    	}
    
    	PUGI__FN xml_node::xml_node(xml_node_struct* p): _root(p)
    	{
    	}
    	
    	PUGI__FN static void unspecified_bool_xml_node(xml_node***)
    	{
    	}
    
    	PUGI__FN xml_node::operator xml_node::unspecified_bool_type() const
    	{
    		return _root ? unspecified_bool_xml_node : 0;
    	}
    
    	PUGI__FN bool xml_node::operator!() const
    	{
    		return !_root;
    	}
    
    	PUGI__FN xml_node::iterator xml_node::begin() const
    	{
    		return iterator(_root ? _root->first_child : 0, _root);
    	}
    
    	PUGI__FN xml_node::iterator xml_node::end() const
    	{
    		return iterator(0, _root);
    	}
    	
    	PUGI__FN xml_node::attribute_iterator xml_node::attributes_begin() const
    	{
    		return attribute_iterator(_root ? _root->first_attribute : 0, _root);
    	}
    
    	PUGI__FN xml_node::attribute_iterator xml_node::attributes_end() const
    	{
    		return attribute_iterator(0, _root);
    	}
    	
    	PUGI__FN xml_object_range<xml_node_iterator> xml_node::children() const
    	{
    		return xml_object_range<xml_node_iterator>(begin(), end());
    	}
    
    	PUGI__FN xml_object_range<xml_named_node_iterator> xml_node::children(const char_t* name_) const
    	{
    		return xml_object_range<xml_named_node_iterator>(xml_named_node_iterator(child(name_), name_), xml_named_node_iterator());
    	}
    
    	PUGI__FN xml_object_range<xml_attribute_iterator> xml_node::attributes() const
    	{
    		return xml_object_range<xml_attribute_iterator>(attributes_begin(), attributes_end());
    	}
    
    	PUGI__FN bool xml_node::operator==(const xml_node& r) const
    	{
    		return (_root == r._root);
    	}
    
    	PUGI__FN bool xml_node::operator!=(const xml_node& r) const
    	{
    		return (_root != r._root);
    	}
    
    	PUGI__FN bool xml_node::operator<(const xml_node& r) const
    	{
    		return (_root < r._root);
    	}
    	
    	PUGI__FN bool xml_node::operator>(const xml_node& r) const
    	{
    		return (_root > r._root);
    	}
    	
    	PUGI__FN bool xml_node::operator<=(const xml_node& r) const
    	{
    		return (_root <= r._root);
    	}
    	
    	PUGI__FN bool xml_node::operator>=(const xml_node& r) const
    	{